Tyler Conover Tyler Conover - 1 year ago 165
Javascript Question

Event Handler Namespace in Vanilla JavaScript

I'm familiar with namespaces in jQuery's event handlers. I can add an event handler in a specific namespace:

$('#id').on('click.namespace', _handlerFunction);

And then I can remove all event handlers in that namespace:


The advantage here is that I can remove only the events in this namespace, not any user-added/additional events that should be maintained.

Does anyone have any tips on how I can not use jQuery, but achieve a similar result?

Thank you!!

Answer Source

I think you are looking for addEventListener and removeEventListener. You can also define custom events and fire them using dispatchEvent.

However, to remove an event listener, you will need to retain a reference to the event function to remove just the function you want to remove instead of clearing the whole event.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download