jQuery Kochbuch

Page 229

})(jQuery);

name needs to be the method name we want to override, for example: jQuery.broadcast('addClass');

Triggering an event prior to the execution Now that we have put our own function as the jQuery method, let’s see how to trigger an event that will allow us to change the incoming arguments: // Create an event object var e = $.Event('before-'+name); // Save the arguments into the object e.args = $.makeArray(arguments); // Trigger the event this.trigger(e);

Assuming you’re broadcasting addClass(), we can now do this: jQuery('body').bind('before-addClass',function(e){ e.args[0]; // The CSS class });

Executing the original method An event is now triggered, but we still have to call the old addClass(). We’ll save the returned data into the event object as well so we can expose it later when we trigger the other event. e.ret = old.apply(this, e.args);

As you can see, we don’t pass the original arguments array; instead, we use the one we exposed in case it was modified in some way.

Triggering an event after the execution We now have the returned data saved in our event object. We can now trigger the final event, allowing external modification of the returned data. We’ll reuse the same event object, but we’ll change the event’s name. e.type = 'after-'+name; this.trigger(e);

Returning the result All what’s left now is to return the resulting data and continue with the normal execution. We’ll give out what we saved on e.ret that could have been modified by an event handler: return e.ret;

206 | Chapter 9: Advanced Events


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.