views:

497

answers:

2

I'm looking for a way to dispatch an event from my jQuery plugin so that it can have multiple listeners for that event. I have the plugin setup so that it returns a reference to itself so that I can add listeners later via public methods.

The only examples I've seen so far have a single event handler, e.g.:

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

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

Is my only option what I was going to do, simply have an array of registered event handlers and call each of them, or am I missing a better alternative.

A: 

why not use an array and loop through it? The code below will accept both an array and a single event handler.

$.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] })
Marius
Yes that is what I was thinking (although there will be a registerEventHandler method so I can register handlers later) but I wondered if there was a better (or should I say standard/core to jQuery) alternative.
DEfusion
+2  A: 

I'd go with throwing an array into the constructor/options object. This is how it's normally done:

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

And the plugin would do something along the lines of this:

Assuming you are writing a plugin which is supposed to be executed on a collection.

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

        while (i--) options.eventsToFire[i]();
    });
};
roosteronacid
You could potentially shorten the while statement by decrementing at the start, `while ( i--; ) { }`
meder
You are right. Pretty nifty :)
roosteronacid
Yeah this is pretty much what I thought. The only difference is I have a registerEventHandler method on the plugin so I can add event handlers later.
DEfusion