Unable to remove jQuery event listener attached with event.data in Javascript

Viewed 126

I'm having trouble removing jQuery event listener using jQuery .off(), which is attached to a button with event.data. Here is the code which I've developed to perform the desired action:

function test1(){
    //some data to be used on click at button 'lets go'
    var i=1;
    function test2(event){
        event.data.i++;
        console.log("i="+event.data.i);
        console.log("i_original="+i);
    }

    $('#letsGo').off('click'); //cannot use, as it is required in global scope with different handler function
    $('#letsGo').off('click', test2); //not working
    $('#letsGo').off('click', {'i':i}, test2); //not working
    $('#letsGo').off('click', {'i':i}, test2(event)); //not working
    $('#letsGo').off('click', test2(event)}; //not working
   
    //some code here
    $('#letsGo').on('click', {'i':i}, test2); //this is where it get's attached after removing existing handler
}

The above function is called in the below sequence of operations:

test1() //function call
    click @ letsGo
    click @ letsGo
    click @ letsGo
test1() //again function call to remove existing handlers and attach new one
    click @ letsGo
test1() //again function call
    click @ letsGo
    click @ letsGo
.....continues

The problem with above jQuery .off() approach is it's not removing the existing event, instead it's always attaching a new one. Because of this whenever a function call is made, there will be one more event listener. This is not the desired behaviour.

All I want with this function is .off() to work, even though there is event.data property.

So, please help me with this.

1 Answers

First, namespace your event when you attach it:

$('#letsGo').on('click.test2', {'i':i}, test2);

Then, when you want to remove only the test2 function, target it with the namespace you created earlier:

 $('#letsGo').off('click.test2');
Related