JAVASCRIPT CUSTOM EVENTS

JavaScript Custom Events

Despite the huge number of events JavaScript provides out of the box for a whole horde of scenarios, there will be times when the user wants to fire his/her own events for their certain needs.

There are many reasons for why the user might want to do that. Events provide a level of decoupling between the thing that fires the event and the thing that listen for that event. In the event-driven world that we live in, the DOM elements doesn’t need to be familiar with the inner workings of the code. By relying on events, the user has a great deal of flexibility in changing things around in the UI or in the code without breaking things and doing a lot of clean-up afterwards. This makes the built-in events and custom events created by the user more useful.

To take advantage of this usefulness, JavaScript provides the user with just what they need. The user might have named Custom Event that does all sorts of amazing things, and in this article, we’ll take a detailed look at it.

JavaScript Custom Events

CREATING EVENTS

The user can use the Event constructor to create an event. The first and most important argument is the name of the event.

1 const customEvent = new Event(‘custom’);
2
3 document.addEventListener(‘custom’, function(event) {
4 console.log(customEvent === event); // true
5 });
6
7 document.dispatchEvent(customEvent);

The event will not bubble by default. To change the behaviour the user has to pass additional options to the constructor.

const customEvent = new Event(‘custom’, { bubbles: true });

Events such as the above are generally referred as synthetic. The function dispatchEvent used above invokes event handlers synchronously, instead of doing it asynchronously through the event loop.

Custom Event

1 const profilePicture = document.querySelector(‘#profilePicture’);
2 profilePicture.addEventListener(‘userSignedIn’, function(event) {
3 event.target.src = event.details.profilePicture;
4 });
5
6 signInUser(credentials)
7 .then(function(userData){
8 const userSignedInEvent = new CustomEvent(‘userSignedIn’, {
9 detail: userData
10 });
11 profilePicture.dispatchEvent(userSignedInEvent);
12 }))

Just remember that if the user would like to stop the propagation of the events at some point, the user need to add cancellable: true to the event options.

BUILT-IN EVENTS

The user might want to simulate an event, that occurs natively in the browser. The instance of that is the “click” event. Imagine having a checkbox:

1 <input type=”checkbox” />

const checkbox = document.querySelector(‘input[type=”checkbox”]’);
checkbox.addEventListener(‘change’, function(event) {
console.log(‘State was changed’);
});

The difficulty will occur when the user will try to change its state programmatically, through the JavaScript code:

checkbox.checked = true; // the event wasn’t fired

Running the code above will not cause the event to be fired. The user can easily fix that with a custom event.

const clickEvent = new MouseEvent(‘click’);

checkbox.dispatchEvent(clickEvent); // the event was fired

This code will cause “State was changed” to be displayed in the console.

Just note that due to some implementation changes between browsers, trying to dispatch the same MouseEvent twice might fail.

The code below works fine on Firefox, but on Chrome the second dispatchEvent does not work.

2 checkbox.dispatchEvent(clickEvent); // “State was changed”
checkbox.dispatchEvent(clickEvent); // nothing happens

To ensure that the event is dispatched every time, use a brand new event.
checkbox.dispatchEvent(new MouseEvent(‘click’));

CONCLUSION

In our opinion custom events are just better all around. We do think they require a bit more communication though. The user will probably have to write up some comments somewhere that explain what custom events are fired and when and how to make that easy to discover.