manikanta manikanta - 2 years ago 79
Javascript Question

What is the difference between different ways of Custom event handling in JavaScript?

I came across the below posts about custom event handling in JavaScript. From these articles, there are two ways (at least) of handling/firing custom events:

  1. Using DOM methods (createEvent, dispatchEvent)

  2. Custom code

But what is the recommended way of handling (firing & subscribing) custom events?

[Edit] The context for this question is not using any libraries like jQuery, YUI,... but just plain JavaScript

[Edit 2] There seems to be a subtle differences, at least with the error handling.
Dean Edwards ( ) is recommending the former way for custom event handling. Ca we say this a difference?

Answer Source

What your describing is the difference between

  • A custom event based message passing system
  • manually firing DOM events.

The former is a way to use events for message passing. An example would be creating an EventEmitter

The latter is simply a way to use the browsers build in DOM event system manually. This is basically using the DOM 3 Event API which natively exists in (competent / modern) browsers.

So the question is simply what do you want to do? Fire DOM events or use events for message passing?

Benchmark showing DOM 3 custom events is 98% slower

The DOM appears to have a huge overhead. It does so because it supports event propagation and bubbling. It does because it supports binding events to a DOMElement.

If you do not need any of the features of DOM3 events then use a pub/sub library of choice.

[Edit 2]

That's all about error handling, how you do error handling is upto you. If you know your event emitter is synchronous then that's intended behaviour. Either do your own error handling or use setTimeout to make it asynchronous.

Be wary that if you've made it asynchronous you "lose" the guarantee that the event handlers have done their logic after the emit/trigger/dispatch call returns. This requires a completely different high level design then the assumption that event emitters are synchronous. This is not a choice to make lightly

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