Passing ''Arguments'' into Event listeners

If you are using one event handler function for multiple event listeners, it would be helpful to pass arguments into the event handler. Unfortunately, you can't do that the normal way in JavaScript, although there are some workarounds. In this article, I am going to explain how to do that with brief examples.

The wrong way

Trying to pass arguments directly to the event handler in the event listener expression will not do any good

const clickHandler = function (e, color) {
 e.target.style.backgroundColor = color;
}
buttonOne.addEventListener('click',clickHandler(e, 'red') )

In the above piece of code, the desired outcome is to change the clicked button's color to red as we pass it into the handler, but obviously, that's not working. The reason behind it is that when you add braces into the event handler function, it will be called immediately not when the event fires.

Using Anonymous functions

const clickHandler = function (e, color) {
 e.target.style.backgroundColor = color;
}
buttonOne.addEventListener('click', function(e) {
 clickHandler(e, 'red')
} )

One way to get the desired outcome is to pass an anonymous function into the event listener, which will be called when the event fires. We will call the handler function inside the anonymous function with the appropriate arguments.

Modifying the 'this' object

Another way of solving the problem at hand is to use the bind() function to modify the 'this' object. The 'this' object in turn will be used as an argument in the handler function.

const clickHandler = function (e) { 
e.target.style.backgroundColor = this;
}
buttonOne.addEventListener('click', clickHandler.bind('red'))

The 'this' object in the above example is modified to be 'red'. This workaround is not actually passing arguments, but it gives a cleaner solution.

This hack won't work if the handler function is an arrow function (remember what 'this' means in arrow functions)

One more thing, if you want to pass multiple arguments into the handler function, you can modify the 'this' object into an array or an object as in the code below.

const clickHandler = function (e) { 
e.target.style.backgroundColor = this[0];
e.target.style.color = this[1]
}
buttonOne.addEventListener('click', clickHandler.bind(['red', 'white']))

Conclusion

Reusing event handlers with different arguments is an elegant way of handling multiple events with just one function. Passing arguments into the event listener expression may not be possible directly but we can do this using an anonymous function that calls the handler when needed. If you think it is ugly this way or you want to do it with fewer keystrokes, modifying the 'this' object into an argument object will do so.

No Comments Yet