2

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

Ajain Vivek
  • 1,111
  • 1
  • 12
  • 20
  • This might be relevant: http://stackoverflow.com/a/3222540/551093 – Christian Feb 22 '13 at 14:13
  • I'm cursious as to why this question is being asked. It seems to imply that you're aware that *named* event listeners can be removed, and that would be a simple change. Is it that you absolutely cannot change that piece of code, and you are looking for a workaround however ugly? You may be able to hijack the `addEventListener` by prototyping, to a proxy function that stores a named reference of the listener. Terrible? Yes. – David Hedlund Feb 22 '13 at 14:21
  • [Proof of concept](http://jsfiddle.net/6LduX/) of what I'm talking about above. – David Hedlund Feb 22 '13 at 14:31

3 Answers3

3

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 );
whitneyit
  • 1,226
  • 8
  • 17
3

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

Demo: http://jsfiddle.net/jrXex/2/

techfoobar
  • 65,616
  • 14
  • 114
  • 135
2

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().

Timmetje
  • 7,641
  • 18
  • 36