event-utils
v2.1.1
Published
An event utils system written in ES6.
Downloads
123
Readme
event-utils
An event utils system written in ES6.
Installation
npm install event-utils
Usage
import EventEmitter from "event-utils";
const emitter = new EventEmitter();
// foo on
function callback1(arg) {
console.log("callback1 called", arg);
}
function callback2() {
console.log("callback2 called");
}
function callbackOnce() {
console.log("callback called once");
}
emitter.on("foo", callback1);
emitter.on("foo", callback2);
emitter.once("foo", callbackOnce);
// bar on
function callbackBar() {
console.log("callbackBar called");
}
emitter.on("bar", callbackBar);
// Emit foo and bar
emitter.emit("foo", "arg");
emitter.emit("bar");
emitter.emit("foo"); // To test once
// Off
emitter.off("foo");
// Emit bar
emitter.emit("bar");
// off all = off bar
emitter.off("bar");
// Emit with no callbacks
emitter.emit("bar");
emitter.emit("foo");
API
EventEmitter
An event utils system written in ES6.
Kind: global class
- EventEmitter
- new EventEmitter()
- .on(event, cb) ⇒ EventEmitter
- .once(event, cb) ⇒ EventEmitter
- .off(event, cb) ⇒ EventEmitter
- .emit(event, ...cbs) ⇒ EventEmitter
- .listeners(event) ⇒ Array.<function()>
- .hasListeners(event) ⇒ boolean
new EventEmitter()
Creates an instance of EventEmitter.
eventEmitter.on(event, cb) ⇒ EventEmitter
Add callback to event
Kind: instance method of EventEmitter
| Param | Type | | ----- | --------------------- | | event | string | | cb | function |
eventEmitter.once(event, cb) ⇒ EventEmitter
Add callback to event and remove on first call
Kind: instance method of EventEmitter
| Param | Type | | ----- | --------------------- | | event | string | | cb | function |
eventEmitter.off(event, cb) ⇒ EventEmitter
Remove callback from event
Kind: instance method of EventEmitter
| Param | Type | | ----- | --------------------- | | event | string | | cb | function |
eventEmitter.emit(event, ...cbs) ⇒ EventEmitter
Emit an event with arguments
Kind: instance method of EventEmitter
| Param | Type | | ------ | ------------------- | | event | string | | ...cbs | args |
eventEmitter.listeners(event) ⇒ Array.<function()>
Return all callbacks attached to an event
Kind: instance method of EventEmitter
| Param | Type | | ----- | ------------------- | | event | string |
eventEmitter.hasListeners(event) ⇒ boolean
Return a boolean if the event has listeners
Kind: instance method of EventEmitter
| Param | Type | | ----- | ------------------- | | event | string |
License
MIT. See license file.