Skip to content

Instantly share code, notes, and snippets.

@abravalheri
Created October 5, 2016 13:56
Show Gist options
  • Save abravalheri/d137cf14652eb932f398cdffe06fc7c2 to your computer and use it in GitHub Desktop.
Save abravalheri/d137cf14652eb932f398cdffe06fc7c2 to your computer and use it in GitHub Desktop.

A variation of the Observer pattern have emerged over the past few yes in the JavaScript community. Called Event Emitter, this pattern seems to simplify the implementation and usage of events.

This is especially true for lightweight libraries in dynamic languages, such as Smoke Signals, where there is no Event object. Instead, plain strings are used to notify the event handlers, which are simple callback functions. The influence of jQuery in this pattern is also remarkable: the features can be accessed in an expressive way with short named methods.

Typical EventEmitter implementation provides the following interface:

  1. on(event, callback) - Run callback every time event is emitted;
  2. once(event, callback) - Run callback when event is emitted just for the first time;
  3. off(event, callback) - Removes the callback for event;
  4. off(event) - Removes all callbacks for event;
  5. off() - Removes all callbacks for all events.
  6. emit(type, ... args) - The event callbacks are called with the passed arguments.

on and once usually returns the emitter itself, for chaining methods. It could be useful to return an array or hash table (dictionary) from off methods (respectively for 4 and 5) with the disabled callbacks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment