Cover by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

9.6. Getting Notified When jQuery Methods Are Called

Problem

You want to perform a certain action when a DOM element gets modified using jQuery. This could involve changing an attribute such as a CSS property, removing it from the document, etc.

Some browsers already support mutation events,[21] which would serve this need, but they’re not something you can use in a cross-browser fashion yet, and they aren’t integrated with jQuery.

Another thing you might ever need is to modify the arguments passed to jQuery methods before they’re executed. On the same principle, you could need to alter the data returned by a method after the executing of the function itself.

Solution

This is somehow related to aspect-oriented programming,[22] but here we won’t be nesting functions; instead, we’ll overload the desired method once and trigger events every time the method is called.

We’ll need one event to be triggered before the function is run to allow the arguments to be changed. We’ll also need an event after the function is run so we can retrieve the returned data and even change it if necessary.

Let’s see how to code this as a plugin. I’ll show you each step separately.

Discussion

Overloading the desired method

First, let’s create a function that replaces jQuery methods with our own function. I’ll name it jQuery.broadcast(); you can change its name if you prefer something else:

(function($){ $.broadcast = function(name){ // Save the original method var old = $.fn[name]; $.fn[name] = function(){ // Broadcast ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required