Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .off doesn't seem to work

so I'll be short: jquery .off() doesn't disable a listen I've set with .on.

html:

<span id="myspan">lol</span>
<button id="b1">jquery On</button>
<button id="b2">jquery Off</button>

js:

$("#b1").on("click", add);
$("#b2").on("click", del);

function add() {
    $("#myspan").on("click", function(e) {
        var a = 1;
        testfunc(a, e);
    });
}

function del() {
    $("#myspan").off("click", testfunc);
}

function testfunc(num, event) {
   alert(num);
}

So first we add to myspan the testfunc() by clicking the jquery On button. After we do that, if we click on the span, we get an alert. Next, we click the jquery off button. That is supposed to remove the listener but it doesn't. Even after that, when we click on myspan testfunc is still attached.

Why? And how can I remove it ?

like image 955
MirrorMirror Avatar asked Jan 11 '14 20:01

MirrorMirror


2 Answers

Your parameters don't match

It doesn't because you bound to a different function (anonymous one). And then you're trying to unbind from testfunc... In order for your event (un)binding to work both parameters between on and off must match.

Possible workaround

If this is the only click event listener on the element, then it's be easiest way to unbind from your anonymous function by calling:

$("#myspan").off("click");

If you're binding several event handlers to click event on the same element then you can also distinguish them by providing namespaces and then use proper namespacing in off call.

$("#myspan").on("click.test", function(e) { ... });
...
$("#myspan").off("click.test");

Or use just namespace if you'd like to unbind several different event handlers that were bound using the same namespace:

$("#myspan").off(".test");
like image 192
Robert Koritnik Avatar answered Nov 15 '22 14:11

Robert Koritnik


You're not binding the event handler to testfunc, you're binding it to an anonymous function, and whitin that function you're just calling testfunc, so you can't automatically unbind that.

It's either

$("#myspan").on("click", testfunc); // bind function

and then

$("#myspan").off("click", testfunc); // unbind function

or to unbind the anonymous function, just

$("#myspan").off("click"); // remove all handlers

or you can also namespace the handler

$("#myspan").on("click.test", function(e) {
    var a = 1;
    testfunc(a, e);
});

and to remove only that handler

$("#myspan").off("click.test");
like image 36
adeneo Avatar answered Nov 15 '22 14:11

adeneo