Is there any possibility to unbind anonymous callback function ...
link.addEventListener("click", function () {
//Any piece of code
}, true);
link.removeEventListener("click", function () {
//Any piece of code
});
Thanks, Ajain
Is there any possibility to unbind anonymous callback function ...
link.addEventListener("click", function () {
//Any piece of code
}, true);
link.removeEventListener("click", function () {
//Any piece of code
});
Thanks, Ajain
No. Because those to anonymouse functions are actually different. It is the same reason why { a: 1 } === { a: 1 }
returns false.
You need to do the following:
var func = function () { ... };
element.addEventListener( 'click', func, false );
element.removeEventListener( 'click', func, false );
Yes. You can do this by saving a handle to the anonymous event handler function somewhere using arguments.callee
and later using this saved reference to unbind the same.
// binding
var el = document.getElementById('foo');
el.addEventListener('click', function(e) {
alert('Hi');
// this is where we save a handle to the anonymous handler
// arguments.callee gives us a reference to this function
el['_ev'] = arguments.callee;
}, false);
// unbinding
var el = document.getElementById('foo'), handler = el['_ev'];
if(handler) {
// here we use the saved reference to unbind it
el.removeEventListener('click', handler);
el['_ev'] = false;
}
Functions are identified by pointer. You have no pointer to your anonymous function, so you have nothing to pass to remove() to tell it which function to remove.
Simply passing a duplicate function doesn't do it, because the duplicate has a different pointer.
You need to stick with assigning the function to a variable, then passing that variable to remove().