Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  91] [ 7]  / answers: 1 / hits: 21452  / 11 Years ago, sat, january 11, 2014, 12:00:00

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 ?


More From » jquery

 Answers
40

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);

[#73240] Friday, January 10, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
christianu

Total Points: 481
Total Questions: 124
Total Answers: 99

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
christianu questions
;