Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it considered a good practice to create and dispatch custom Javascript events?

My web application uses document.createEvent and event.initEvent to create custom events of the generic type Event.

I wonder whether this is considered good practice. On the hand side, this way I can make use of the DOM event system that is already there and do not have to invent and implement my own; on the other hand this may lead to name clashes in case future standardised event models define an event type with the name I have chosen. (Or is it possible to namespace event types?)

I am asking because I have just learnt by browsing stackoverflow that putting custom properties on DOM objects or builtin Javascript objects is considered bad practise.

EDIT I think I have found something: http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#events-CustomEvent

So let me rephrase my question: Am I understanding the quoted section correctly in that it is advised to actually use a CustomEvent inside a web application?

ADDED WARNING I have just noticed that CustomEvent is not supported in Firefox versions before 6. It is supported in current Webkit-based browsers, though.

like image 809
Marc Avatar asked Jun 25 '11 18:06

Marc


People also ask

What does it mean to dispatch event Javascript?

To dispatch an event means to "fire" it. The handlers listening to that event will be called.

What is the purpose of custom events?

Custom events allow us to run the function outside of the script. It is possible to attach events in other file or script and run them. It is possible to attach multiple listeners to the same event. Separation of code from a script is possible as we don't have to include event code in functions.

Can we create custom events?

Creating a Custom Event: To create a custom event we use the Event constructor or CustomEvent interface. The Event constructor creates an Event and CustomEvent creates an Event with more functionality. The below steps are followed in order to create one using a new Event. We create an event using the Event constructor.

What is a custom event in Javascript?

A custom event can be created using the event constructor, like this: const myEvent = new Event('myevent', { bubbles: true, cancelable: true, composed: false }) In the above snippet, we created an event, myevent , by passing the event name to the Event constructor.


1 Answers

If you're going to create something and make it as namespace-proof as you can, you can do what Webkit and Mozilla do and add a name-moniker to the beginning of all of your event names. Like:

_marc_trap_door_shut
_marc_trap_door_open
_marc_trap_door_ajar
... etc ...
like image 186
Jared Farrish Avatar answered Oct 04 '22 00:10

Jared Farrish