OnEmit
Event emitter that returns the event on emit [ .on() / .emit() / .emitAsync().then() ]
Take control of your events!
This is a vanilla JS event system.
As oposed to "emit-and-forget" systems, this library allows you to do stuff after all event listeners have been executed.
Usage
Include the library - it is an UMD module, works in Browser and Node.js.
var OnEmit = ;
OnEmit
instance:
var emitter = ; // Add event listenersemitter; // Emit events // full versionvar event = emitter; // object eventemitter;// short versionemitter; console; // -> { type: "anything", timeStamp: 1453059701092, result: [return1, return2, ...] } // Remove event listenersemitter;
As a mixin:
The OnEmit
may also be used as a mixin.
For example a "plain" object may become an emitter,
var user = name: 'dima' ;;uservar event = user;
prototype
mixin:
As a You may extend an existing prototype.
;var emitter = ;var event = emitter;
emitter
to an object
Bind var emitter = ;var user = name: 'dima' ;emitter;user;var event = user;
event
handler fn
.
Register an emitter;
event
should be an event name (String), or "*" to catch all events.fn
is an event handler of formfunction fn(emittedEvent, ...) { /*...*/ return value; }
.emittedEvent
is instance ofOnEmit.Event
.- The returned
value
goes intoemittedEvent.result[idx]
.value
could be a promise (used with.emitAsync()
).
event
handler fn
only once.
Register an emitter;
event
handler fn
Register a single-shot removed immediately after it is invoked the first time.
emitter;
event
with a Promise.
Wait for emitter; // reject after 10 secondsemitter;
event
listener(s)
Remove emitter;
- Pass
event
andfn
to remove a listener. - Pass
event
to remove all listeners on that event. - Pass nothing to remove all listeners on all events.
event
with variable option args.
Emit an var event = emitter;
event
argument can be either an
event name (String
),
event properties (Object
) including at least .type
property,
or an OnEmit.Event
instance.
.emit()
returns an OnEmit.Event
instance, which contains an array .result
of whatever
event listeners have returned.
Event handlers can manipulate event
properties before return.
event
asynchronously.
Emit an emitter;
emitAsync
uses OnEmit.setImmediate
or setImmediate
, if available, or setTimeout
otherwise.
event
after delay
milliseconds.
Emit an emitter;
emitAfter
uses OnEmit.setTimeout
or setTimeout
.
Get the array of callbacks
emitter;
event
handlers.
Check if this emitter has emitter;
fn
.
Check if this OnEmit has a specific event handler emitter;
*
listens on all events.
The special event emitter;emitter; // -> fn('foo');emitter; // -> fn('bar');emitter;