JQuery dispatches an event from a plugin for multiple listeners

I am looking for a way to dispatch an event from my jQuery plugin so that it can have multiple listeners for this event. I have a plugin setup so that it returns a link to itself, so that later I can add listeners via public methods.

The only examples I've seen so far have one event handler, for example:

$.fn.foo = function( options ) {
    ...
    // trigger event
    options.eventHandler();
}

$('#bar').foo({ eventHandler: myEventHandler })

I am the only option that I am going to do, it just has an array of registered event handlers and I call each of them, or I do not see a better alternative.

+3
source share
2 answers

constructor/options. :

$("").plugIn(
{
    prop: "value",
    foo: "bar",
    eventsToFire: [
        function () { },
        function () { },
        function () { }
    ]
});

- :

, , .

jQuery.fn.plugIn = function (options)
{
    return this.each(function ()
    {
        var i = options.eventsToFire.length;

        while (i--) options.eventsToFire[i]();
    });
};
+2

? , .

$.fn.foo = function( options ) {
    ...
    // trigger event
    if(typeof eventHandler == "Array"){
      for(var i=0; i<eventHandler.length; i++){
        options.eventHandler[i]();
      }
    }else{
      options.eventHandler();
    }
}

$('#bar').foo({ eventHandler: [myEventHandler, anotherEventHandler] })
0

Source: https://habr.com/ru/post/1719237/


All Articles