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:
on(event, callback)
- Run callback every time event is emitted;once(event, callback)
- Run callback when event is emitted just for the first time;off(event, callback)
- Removes the callback for event;off(event)
- Removes all callbacks for event;off()
- Removes all callbacks for all events.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.