Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : Replace Event Listener

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
like image 319
Muhammad Talha Akbar Avatar asked Dec 25 '22 18:12

Muhammad Talha Akbar


1 Answers

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.

  1. Use something like GlobalEventHandlers which is simple as target.onclick = functionRef;. Mozilla even warns:

    Only one onclick handler can be assigned to an object at a time.

  2. 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(), then seconAction(), then first again...:

        const buttonOne = document.getElementById('buttonOne');
        buttonOne.addEventListener('click', listenerFunction);
    
        let doAction = firstAction; //assigning doAction to firstAction
    
        function listenerFunction() {
            doAction(); //external function call
        }
        function firstAction() {
            doAction = secondAction; //assigning doAction to secondAction
            console.log('first action clicked');
        }
        function secondAction() {
            doAction = firstAction; //assigning doAction to firstAction
            console.log('second action clicked');
        }
        <button type="button" id="buttonOne" name="button">button1</button>

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

like image 70
arty marty Avatar answered Jan 11 '23 04:01

arty marty