How To Create Custom Event Listeners in JavaScript

How can creating custom event listeners be useful in your code base?

Ashwin Kumar
Nov 15 · 3 min read
Image for post
Image for post

JavaScript in browser environment uses an Event Driven Architecture. What it means is we can execute our code in response to certain user behaviours like clicking a button or focusing an input.

The important thing here is that DOM (Document Object Model) is a system that provides us the access to interact with the Document and our code is not directly connected. We need our system to be able to respond to different DOM events and event listeners are the way we couple our system to the DOM to make it interactive.

The idea here is to be able to connect two systems to be able to respond to each other’s behaviours.

So let’s say if you have a big code base where you have different independent components doing different tasks, you might want a communication medium between them and that’s where event listeners come to the rescue.

Under such scenarios, we can create our own events and bind our code to it to be triggered later whenever needed.

The glue for such system would be a global object to which we can attach all these functions and refer to them with a key. This key can be later used to trigger these functions at a later point when needed.

The initial task is creating a class that can return you an object with all the methods needed. If you need only one instance, you can also create a simple object for the same.

After that, the first important method we need would be to attach a callback function on a particular event that we can name according to our likes.

In this method we create an object property by the name of the event which will hold an array of callback functions that can be called later when the event is triggered.

While manipulating existing properties keep the checks to ensure that you’re not targeting any existing properties in the prototype chain.

Assuming we attach let’s say callback1, callback2 and callback3 to an event named ‘logger’ using ‘on’ method, we should have something like this as output:

{'logger':[callback1, callback2, callback3 ]}

Once we emit this event, we should call and execute all the callback functions attached to this event, for which we can use a method like shown below:

While emitting a particular event we can also pass some information as arguments related to the event which will be passed down to the callbacks.

Usually this would be fine to get going with event handling however one of the drawbacks or side effects of using an event handler is that the global object will always be alive as long your code is running and whichever functions you attach with the events along with the data attached to them through closures will not be collected by the garbage collector. Here’s a tiny example:

Here, deleteData function reassigns variable maindata however the defined object still remains in reference through eventhandler which can be checked by emitting the event anytime as shown in the above example.

To avoid such memory leaks, we need to remove the callbacks as soon as they are not required, which can be done as shown below:

We can also add one more method to delete the event property itself if the event is not required anymore.

Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

That’s all from my side, if you need an npm package, here is the link to the same:

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store