DEV Community

Vasyl Stokolosa
Vasyl Stokolosa

Posted on

Review. Event dispatcher based on the CustomEvent interface

I will appreciate some review for CustomEvent package https://github.com/shystruk/custom-event-js.

The Custom Event Dispatcher provides the ability to communicate inside your application by dispatching events and listening to them. It works in all popular browsers, including Internet Explorer 9 and higher.

This is one of the best ways to communicate between your components (universal).

Thanks!

Top comments (8)

Collapse
 
theoutlander profile image
Nick Karnik •

What problem is this solving that existing PubSub libraries don't? Why can't native events be used instead?

Collapse
 
shystruk profile image
Vasyl Stokolosa •

It is based on native CustomEvent api.

Collapse
 
theoutlander profile image
Nick Karnik •

I would try to keep the signature of your library as close to CustomEvent as possible.

Also, if I read it correctly, you don't support the ability to remove a specific event handler by passing it into OFF.

In addition, the methods should be lowercased IMO.

Thread Thread
 
shystruk profile image
Vasyl Stokolosa • • Edited

It removes an event from CustomEvent listener and from EVENTS object.

OFF: function(eventName) {
TARGET.removeEventListener(eventName, EVENTS[eventName]);
delete EVENTS[eventName];
}

Thread Thread
 
theoutlander profile image
Nick Karnik • • Edited

What if I have multiple listeners for the same event?

For instance, if five components want to listen to the USER_LOGIN event. If I remove one of the USER_LOGIN listeners, it will remove them all.

Thread Thread
 
shystruk profile image
Vasyl Stokolosa •

You may have multiple listeners, but when you want to remove them you will remove only the last.

TARGET.removeEventListener(eventName, EVENTS[eventName]);

Good point here. Should think about that.

Thread Thread
 
theoutlander profile image
Nick Karnik • • Edited

Don't just remove the last added. The user needs complete control.

Usually, this is how I would expect it to be used:

let listener = () => {...}
obj.addEventListener('event', listener)
obj.removeEventListener('event', listener)

Another variation is:

let listenerHandler = obj.addEventListener('event', () => {...})
obj.removeEventListener('event', listenerHandler)

Simply calling this should remove all listeners:

obj.removeEventListener('event')
Thread Thread
 
shystruk profile image
Vasyl Stokolosa •

removeEventListener required a handler
developer.mozilla.org/en-US/docs/W...
so, you have to call remove for all listeners and pass the handler function