Skip to content Skip to sidebar Skip to footer

Add Callback To .addeventlistener

Suppose I have this straightforward event listener registration pattern: function registerElement(){ var element = document.getElementById('element'); element.addEventLi

Solution 1:

Event listeners are executed in the order added to an element. Again, provided sayHello does nothing asynchronous that would require the cleanup callback to be be delayed and called asynchronously as well, you could just add another event listener:

functionregisterElement(callback){
     var element = document.getElementById("element");
     element.addEventListener("click", sayHello, false);
     element.addEventListener("click", callback, false); 
}

If cleanup is dependent on sayHello completing an aysnchronous task, the design probably needs reviewing to use promises or async/await functions.

A more generic registration function could parameterize the element id, the type of event and take an arbitrary number of callbacks, (including sayHello) as in this example:

functionregister( elementId, eventType, ...callbacks) {
    const element = document.getElementById( elementId);
    for( const callback of callbacks) {
        element.addEventListener( eventType, callback, false);
    }
}

// testconstsayHello = e=>console.log("hello");
constcleanup =  e=>console.log("cleanup");
register( "myButton", "click", sayHello, cleanup);
<buttontype"button" id="myButton">myButton</button>

Solution 2:

To avoid a mix of responsibilities, a recommendation is to execute the callback function outside of the function sayHello, otherwise the function sayHello will be tied to a second param callback:

This approach is assuming that sayHello doesn't execute any async logic within it

functionregisterElement(callback){
   var element = document.getElementById("element");
   element.addEventListener("click", function(e) {    
      sayHello(e);
      callback();
   }, false);
}

Post a Comment for "Add Callback To .addeventlistener"