JavaScript / jQuery: listening for newly registered event handlers

I am currently working on a project for my university. One thing I need to do is synchronize all registered javascript event handlers with the server. That is, I need to know which elements have a specific event handler.

I already use VisualEvent to find out what elements event handlers have, and it works great.

But I need to have an event listener that is called every time an event handler is registered for the DOM element.

So, basically every time something like $("#foo").click(...)or is called $("#foo").bind(...), I need to get information that a new event handler has been registered for this element.

And vice versa. I need a listener when the event handler is removed from the DOM element, but this is not necessary for the first prototype.

Is there a way to bind a handler globally to all event handler loggers?

If you need more information, feel free to comment.

Thanks in advance for your help!

Regards, Robert

+5
source share
1 answer

If you use jQuery 1.7+, all methods for attaching events go through jQuery.fn.on, so this is a simple case of reinstalling this function and moving to it,

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

}());

jQuery < 1.7 , - , bind(), live(), delegate() ..

+8

All Articles