detach and reattach event listeners

3.9k views Asked by At

Is there a way to detach and reattach event listeners assuming I don't know the function that was attached in the first place?

//Unknown click function
$(target).click(function(e){
    //some function
});

//code to detach click function
$(target).mousedown(function(e){
    if(/*something*/){
        //The next line does not work. What could be done instead?
        this.clickFunction = $(target).click;
        $(target).off("click");
    }
});

//code to reattach click function
$(target).mouseup(function(e){
    if(this.clickFunction){
        $(target).click(this.clickFunction);
        this.clickFunction = null;
    }
});
2

There are 2 answers

0
Tony Brix On BEST ANSWER

jQuery saves the event functions internally as:

$._data(target, "events")

Where "target" is a DOM element not a jQuery object.

https://stackoverflow.com/a/2518441/806777

So the example code would be:

//Unknown click function
$(target).click(function (e) {
    //some function
});

//code to detach click function
$(target).mousedown(function (e) {
    if (/*something*/) {
        this.clickFunctions = [];
        var click = $._data(target, "events").click;
        for(var i = 0; i < click.length; i++) {
            this.clickFunctions.push(click[i].handler);
        }
        $(target).off("click");
    }
});

//code to reattach click function
$(target).mouseup(function (e) {
    if (this.clickFunctions) {
        for (var i = 0; i < this.clickFunctions.length; i++) {
            $(target).click(this.clickFunctions[i]);
        }
        this.clickFunctions = null;
    }
});

https://jsfiddle.net/UziTech/176fzorn/

5
Shijin TR On

Use jquery unbind() like as below to detach,

$(target).unbind('click');
$(target).unbind('mousedown');
$(target).unbind('mouseup');

And you can reattach using bind()

$(target).bind('click',function(){
  //some code
});
 $(target).bind('mousedown',function(){
//some code
});
 $(target).bind('mouseup',function(){
 //some code
});