XF 2.0 Accessing JS handler functions from outside

CMTV

Well-known member
Hi!

Let's say I have two element handlers: A and B:
JavaScript:
XF.A = XF.Element.newHandler({
    init: function() {},

    test: function()
    {
        return 'hey!';
    }
});

XF.B = XF.Element.newHandler({
    init: function()
    {
        // How to call "test()" function from A handler?
        var result = /* XF.A.test() */
    }
});

XF.Element.register('A', 'XF.A');
XF.Element.register('B', 'XF.B');

So how can I get 'hey!' from test() function inside B handler?
 
If your test function doesn't depend on the handler/instance, then move it out of the element handler system and just call it like a general JS function.

If it does depend on the handler, then you need to get the specific instance. I'll just paste some code where the rich text editor needs to know something about the form-tied draft system that hopefully makes the concept fairly clear:
Code:
var draftHandler = XF.Element.getHandler($form, 'draft');
if (!draftHandler)
{
   console.error('No draft handler on parent form');
   return;
}

if (val == 'xfDraftSave')
{
   draftHandler.triggerSave();
}
else if (val == 'xfDraftDelete')
{
   draftHandler.triggerDelete();
}
(This is in editor.js, around line 1950.)
 
Thank you! It helped me to get rid of many .trigger() weird stuff!

Here is the solution for first post case:
JavaScript:
XF.A = XF.Element.newHandler({
    init: function() {},

    test: function()
    {
        return 'hey!';
    }
});

XF.B = XF.Element.newHandler({

    options: {
        // Creating an option with handler element selector
        handlerAElement: '[data-xf-init~=A]'
    },

    // Here we will contain the A handler
    handlerA: null,

    init: function()
    {
        // Getting the A handler
        this.handlerA = XF.Element.getHandler($(this.options.handlerAElement), /* data-xf-init --> */ 'A');

        // Can't find the A handler
        if (!this.handlerA instanceof XF.A)
        {
            console.warn('Can\'t find an element with an XF.A handler!');
            return false;
        }

        // HEY!!!
        var result = this.handlerA.test();
    }
});

XF.Element.register('A', 'XF.A');
XF.Element.register('B', 'XF.B');
 
Back
Top Bottom