Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
  • How do I create a custom event class in Javascript?
  • http://the.unwashedmeme.com/blog/2004/10/04/custom-javascript-events/

  1. Custom code
  • http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/
  • http://www.geekdaily.net/2008/04/02/javascript-defining-and-using-custom-events/

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 ( http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/ ) is recommending the former way for custom event handling. Can we say this a difference?

like image 566
manikanta Avatar asked Jul 04 '11 10:07

manikanta


1 Answers

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

like image 79
Raynos Avatar answered Oct 02 '22 23:10

Raynos