Tuesday, 10 July, 2018 UTC


In the previous article, we’ve learned what events are and how to work with them. This time we will dive a bit deeper into them, explaining in more details how do they work. We will go through the event object and create our own, custom events. We will also simulate some native events that take place in the browser. Let’s go!
Event object
Event.prototype is an object that all events inherit from.
If you would like to know more about prototypes, check out Prototype. The big bro behind ES6 class
The event object contains methods and properties common for all events. There are many types of events: for a complex list of them visit MDN web docs. Some of them have their own prototypes, but they all inherit from the Event.prototype
Event.prototype.isPrototypeOf(MouseEvent.prototype); // true
All these event prototypes have names ending on “Event“, such as “MouseEvent

Creating events

You can use the Event constructor to create an event. The first and most important argument is the name of the event.
const customEvent = new Event('custom');

document.addEventListener('custom', function(event) {
  console.log(customEvent === event); // true

If you would like to make it work on the Internet Explorer, consider using createEvent function instead. For more details see the browser compatibility table.
Note, that the event will not bubble by default. To change that behaviour, pass additional options to the constructor:
const customEvent = new Event('custom', { bubbles: true });
If you are not sure what bubbling means, consider checking out Understanding events. Bubbling and capturing
Events such as the one above are commonly referred to as synthetic. The function 
 used above invokes event handlers synchronously, instead of doing it asynchronously via the event loop.
To read a little more about the event loop, check out When async is just not enough. An introduction to multithreading in the browser


As I’ve mentioned already, there are many types of events. One of them is the CustomEvent, that allows you to pass additional information.
const profilePicture = document.querySelector('#profilePicture');
profilePicture.addEventListener('userSignedIn', function(event) {
  event.target.src = event.details.profilePicture;

        const userSignedInEvent = new CustomEvent('userSignedIn', {
            detail: userData
Just remember that if you would like to stop the propagation of your events at some point, you need to add 
cancelable: true
 to your event options.
You might wonder if you need the custom events at all. CustomEvents might come in handy especially when you are working without modern frameworks and libraries like React, Vue or Angular. They could be also useful when you need to somehow communicate between legacy code written with Vanilla JS and some React components.
Built-in events
You might want to simulate an event, that occurs natively in the browser. The example of that is the “click” event. Imagine having a checkbox:
<input type="checkbox">
It is a common thing to want to react to it being checked somehow. Let’s add an event listener:
const checkbox = document.querySelector('input[type="checkbox"]');

checkbox.addEventListener('change', function(event) {
  console.log('State was changed');
Pretty good so far. The problem will occur when you will try to change its state programmatically, through your JavaScript code:
checkbox.checked = true; // the event wasn't fired
Running the code above will not cause the event to be fired. You 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 differences 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.
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'));
Today we’ve learned more about the Event object itself. To explain it better, we’ve created our own, custom events. It made us use the Event and CustomEvent constructors. We’ve also covered some example of their use-case in the real life. As it might prove useful, we’ve also covered simulating native events, such as the click event. I hope that it helped you a bit in understanding how events work. See you next time!
The post Diving deeper into the Event object. Creating and using custom events appeared first on Marcin Wanago Blog - JavaScript, both frontend and backend.

Diving deeper into the Event object. Creating and using custom events was first posted on July 9, 2018 at 9:22 am.
©2018 "Marcin Wanago Blog - JavaScript, both frontend and backend". Use of this feed is for personal non-commercial use only. If you are not reading this article in your feed reader, then the site is guilty of copyright infringement. Please contact me at [email protected]