I am listening to an event and want to call different methods. For example, I am listening to animation end event and the code is something like this:
this.inAnimationCallback = function() {
console.log('In');
_this.elem.className = _this.settings.className;
};
this.outAnimationCallback = function() {
console.log('Out');
_this.elem.parentNode.removeChild(_this.elem);
};
this.elem.addEventListener(animationEvent, this.inAnimationCallback);
setTimeout(function() {
_this.elem.addEventListener(animationEvent, _this.outAnimationCallback);
// Call some animation here.
}, 3000);
What happens here is that instead of replacing the method attached to the event, JS adds the method and when animation ends, both methods are called. Console looks like this:
(2) In
Out
I'm writing this answer for those like me, who is just started learning JS. And this thread came up first in google to "js replace event listener".. Although, I am not disagreeing with the answers to use
removeEventListener()
, but mozilla warns that this function is not always successful. So use it with care. not willing to go that road i have found two other ways to do it.Use something like GlobalEventHandlers which is simple as
target.onclick = functionRef;
. Mozilla even warns:Within listener function add external function call to action function, and then replace reference to another external action function. For example this code will call
firstAction()
, thenseconAction()
, then first again...:I wrote this answer to broaden solution scope: would have saved at least 6 hours of my time. If I had this in the first place...