I’m trying to remove an event listener for created span elements where the function called is within a closure. I’ve tried various methods and none seem to work.
var MyClass = function () {}
MyClass.prototype.addSpan = function (el) {
var span = document.createElement('span');
span.innerHTML = "Text here";
el.appendChild(span);
span.addEventListener('click', (function (obj) {
return function () {
obj.removeSpan();
}
})(this), false);
}
MyClass.prototype.removeSpan = function () {
alert('removing span');
this.removeEventListener('click', arguments.callee, false);
// .... remove span ....
}
myclass = new MyClass();
myclass.addSpan(document.getElementById('box'));
I’ve also used
this.removeEventListener('click', (function (obj) {
return function () {
obj.removeSpan();
}
})(this), false);
in place of this.removeEventListener('click', arguments.callee, false); but had no luck.
Any help is much appreciated!
Without a reference of the listener you can’t remove it, so I’ve also added a property (listener) to the MyClass’ prototype and then returned the reference as
return obj.listenerand also you need to pass the object as I’ve passed itobj.removeSpan(this);and in theremoveSpanI’ve received withelso I could’ve doneel.removeEventListener, hope it helps.You can also do this
instead of
Here is an example.