Eventable
Eventable is a lightweight asynchronous replacement for node's EventEmitter which also runs beautifully in the browser.
Methods
Eventable has two methods both of which behave very much like a standard
EventEmitter: emitter.on(name, listener)
and
emitter.emit(name, args..., callback)
.
emitter.on(name, listener(args..., [callback]))
This method attaches a listener to an event. Like an EventEmitter, this takes
two arguments, name
and listner(args..., [callback])
. In the listener
function itself, however, there is a key difference. The function's expected
arguments determine whether it is fired asynchronously or not; if listener
includes a callback
argument, it will be invoked asynchronously and the
emitter.emit
callback will not be run until after the listener's callback
has fired.
If listener
runs syncronously, listener
should take as many arguments
as there will be in args
when emitter.emit(name, args..., callbœack)
is
called.
If the event is to be run asyncronously (or might have to run
asyncronously) the emitter arguments must include all args
from
emitter.emit(name, args..., callback)
and, at the end, callback
. If the
listener accepts a callback, it must fire the callback when œit is done
executing.
emitter.emit(name, args..., callback)
The emitter.emit
method also behaves very much like its EventEmitter counterpart
except that it requires a callback. If you are not anticipating any async listeners
(or just want them to run in the background) this callback can be an empty function
but it must be present (or else the last arg will be treated like a callback!).
Example
// Create an emitter
var emitter = new Eventable;
// Add a listener
emitter.on("foo", function(bar) {
// ...
});
// Add an async listener
emitter.on("foo", function(bar, callback) {
setTimeout(function() {
// ...
callback();
}, 1000);
});
// Emit the event
emitter.emit("foo", "baz", function() {
// Doesn't run until the setTimeout is done!
// ...
});
Installation
To install eventable, use npm
npm install eventable
Then Eventable can easily be included into any node.js project
Eventable = require("eventable");