loading...

Review. Event dispatcher based on the CustomEvent interface

twitter logo github logo ・1 min read

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!

twitter logo DISCUSS (8)
markdown guide
 

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

 
 

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.

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

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

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.

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.

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')

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

Classic DEV Post from Sep 30 '19

Hacktoberfest for beginners - Low hanging contribution opportunities

Vasyl Stokolosa profile image
JavaScript enthusiast. Front End Architect.