Add Callback To .addEventListener
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:
function registerElement(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:
function register( elementId, eventType, ...callbacks) {
const element = document.getElementById( elementId);
for( const callback of callbacks) {
element.addEventListener( eventType, callback, false);
}
}
// test
const sayHello = e=>console.log("hello");
const cleanup = e=>console.log("cleanup");
register( "myButton", "click", sayHello, cleanup);
<button type"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
function registerElement(callback){
var element = document.getElementById("element");
element.addEventListener("click", function(e) {
sayHello(e);
callback();
}, false);
}
Post a Comment for "Add Callback To .addEventListener"