Custom events in client side javaScript

In client side javaScript there is the custom event constructor that can be used to create my own events that can be attached to html elements. There are a number of other ways of creating custom events when it comes to using a framework like phaser and threejs. However in this post I will be sticking to the custom way of how to go about making custom events in just plain old vanilla javaScript in the browser.

1 - Custom Event constructor basic example

In this section I will be touching base on just a basic example of the CustomEvent constructor. The process just involves creating an event with the custom event constructor, and then passing that object to the dispatch event method of a DOM element reference. Once the dispatch event method is called any event handlers that are attached for that custom event will fire.

So lets start out with just some basic html like this and attach to an external javaScript file.

1
2
3
4
5
6
7
8
<html>
<head>
<title>custom event in client side javaScript</title>
</head>
<body>
<script src="basic.js"></script>
</body>
</html>

In the basic.js file that I am linking to in the html I am creating a custom event object with the Custom Event constructor, attaching a handler to the body element of the htl document for it, and then dispatching the event for the body element like so.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var myEvent = new CustomEvent(
'my-event', {
detail: {
message: 'custom event!',
time: new Date(),
n: 42
},
bubbles: true,
cancelable: true
});
// define a handler for the event
document.body.addEventListener('my-event', function (e) {
console.log(e.detail.message); // 'custom event!'
console.log(e.detail.n); // 42
});
// dispatch it
document.body.dispatchEvent(myEvent)

This might not be the best example of why creating my own events is a good idea, but you get the basic idea of the process. Just call the Custom event constructor with the new keyword just like any other constructor function in javaScript. When doing so pass the name of the custom event as the first argument, followed by and object. This object should have at least a detail property that contains data about the nature of the event.