Using Browser Custom Events

Wednesday, June 26, 2019

A lot of times when writing things you may want want to react to certain events on your page.

We do this all the time with builtin ones like click or keydown

But we can also make our own custom events and have the browser handle all the work for us! Since it’s part of the DOM API we get free event code without installing another lib or rolling our own buggy version.

CustomEvent is what we will be using. We’ll wrap it a little to make it a bit neater to use as well.

Making a custom event

It’s pretty simple

const event = new CustomEvent("myevent", {details: {some: "data"}});


Notice we had to put our own custom data in the details key of the event. This is just a quirk of how they work.

Listening for a custom event

function eventHandler(event){
	const data =;
document.addEventListener("myevent", eventHandler)

Stopping listening

document.removeEventListener("myevent", eventHandler);

Pretty easy stuff.

What’s great is, we can also dispatch the event on an element so it doesn’t bubble up to the dom. Keeping our code event more modularized. Just replace document with another element you have.

A little wrapper.

Because it’s a little bit cumbersome to have to write all that everytime you want to use an event. Let’s wrap it just a little.

function publish(eventName, data){
	const event = new CustomEvent(eventName, {details: data});
const events = [];
function subscribe(eventName, cb){
	const wrapper =  function(event){
	document.addEventListener(eventName, wrapper);
		cb, wrapper, eventName

function unsubscribe(eventName, cb){
		if(event.eventName === eventName && cb === event.cb){
			document.removeEventListener(eventName, event.wrapper);

export {subscribe, unsubscribe, publish};


function eventHandler(data){
subscribe("myEvent", eventHandler))
publish("myEvent", {some: "data"});
unsubscribe("myEvent", eventHandler);

Et voilĂ 

If you like my stuff please check out my site

This post is also available on DEV.