wecsam
wecsam

Reputation: 2751

Clear Every Event Handler

I would like to cancel every event handler defined in a page with JavaScript. In other words, if the page previously set up many event listeners on many different DOM levels, this method would simply delete every one of them. Is there a way to do this in JavaScript?

Upvotes: 0

Views: 2038

Answers (2)

SeanCannon
SeanCannon

Reputation: 77956

Nope there's no native event list to see what is bound to what. JQuery has its own, if you want better event management.

Here's how it's done in JQuery:

(function($) {
    $.eventReport = function(selector, root) {
        var s = [];
        $(selector || '*', root).andSelf().each(function() {
            var e = $.data(this, 'events');
            if(!e) return;
            s.push(this.tagName);
            if(this.id) s.push('#', this.id);
            if(this.className) s.push('.', this.className);
            for(var p in e) s.push('\n', p);
            s.push('\n\n');
        });
        return s.join('');
    }
    $.fn.eventReport = function(selector) {
        return $.eventReport(selector, this);
    }
})(jQuery);

You can call it various ways to suit your needs:

// all events
alert($.eventReport());

// just events on inputs
alert($.eventReport('input')); 

// just events assigned to this element
alert($.eventReport('#myelement')); 

// events assigned to inputs in this element
alert($.eventReport('input', '#myelement')); 
alert($('#myelement').eventReport('input')); // same result

// just events assigned to this element's children
alert($('#myelement').eventReport()); 
alert($.eventReport('*', '#myelement'); // same result

From there, unbinding is simple.

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

For clearing all the events dynamically attached to elements within the body of the page, you can do:

document.body.innerHTML = document.body.innerHTML;

For clearing events attached to the window object, you can do:

window.onscroll = function() {};

and so on..

Upvotes: 2

Related Questions