I'm currently working on a project for my university. One thing I need to do there is to synchronize all registered JavaScript event handlers with the server. I.e. I need to know which elements have a particular event handler.
I already use VisualEvent to find out which elements have event handlers and it works really great.
But the thing I need is to have an event listener which is called every time an event handler is registered for a DOM element.
So basically every time something like $("#foo").click(...)
or $("#foo").bind(...)
is called, I need to get the information that a new event handler has been registered for this element.
Vice versa I need a listener when a event handler is removed from a DOM element, but this is not mandatory for the first prototype.
Is there a way I can attach a handler globally to all event handler registrations?
If you need any more information, don't hesitate to comment.
If you're using jQuery 1.7+, all methods to attach events go through jQuery.fn.on
, so it's a simple case of over-riding that function and going wild;
(function () {
var old = jQuery.fn.on;
jQuery.fn.on = function (events, selector, data, handler) {
// Ensure you still attach the events
var result = old.apply(this, arguments);
// Now do your own thing
// Inside here, `this` refers to the jQuery object on which `on` was invoked;
// it's not a specific element like it normally is within jQuery. You then
// therefore use something like `this.each(function () { /* this */ }); to
// target each element in the set.
// You might want to normalize the variables, as selector and data are optional,
// and events can be an object or string
jQuery.post('/spy.php', {
events: events,
selector: selector,
data: data
}, jQuery.noop);
return result; // keep the signature of `on`, and return the value `on()` *would* have done.
};
}());
If you're using jQuery < 1.7 and can't upgrade, you can do something similar to above, but will have to override bind()
, live()
, delegate()
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With