Reputation: 15
I am new to OOP in JavaScript!!!
I am trying to remove a eventlistener but can not make it work:
window.addEventListener('resize', this.adapt.eventBind(this), true);
window.removeEventListener('resize', this.adapt.eventBind(this), true);
This is the function that bind the eventlistener:
Function.prototype.eventBind = function(parentObj) {
var func = this;
var args = new Array();
for(var i = 0; i < arguments.length - 1; i++) {
args[i] = arguments[i+1];
}
var temp = function(evt) {
if(typeof(evt) != "undefined") {
if(typeof(evt["target"]) != "undefined") args[0] = evt["target"];
else args[0] = evt["srcElement"];
}
return func.apply(parentObj, args);
}
return(temp);
}
Kind regards
Upvotes: 0
Views: 243
Reputation: 1074485
The function you pass into removeEventListener
has to be the same function you gave addEventListener
; but in your case, you're creating a new, different function.
So you'll have to remember it, perhaps on that same object:
this.resizeListener = this.adapt.eventBind(this);
window.addEventListener('resize', this.resizeListener, true);
window.removeEventListener('resize', this.resizeListener, true);
(Note that even though I use this.resizeListener
when adding/removing, it doesn't have the this
problem code looking like that would normally have, because I've already bound it using your eventBind
.)
Upvotes: 4