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.
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]();
});
};