eventemitter-callback
Emit an event and waiting for a result. Based on eventemitter3.
Installation
By package manager:
npm install eventemitter-callback --save
yarn add eventemitter-callback
Installation from CDN:
<script src="https://unpkg.com/eventemitter-callback"></script>
<script src="https://cdn.jsdelivr.net/npm/eventemitter-callback"></script>
<script>
console.log(EventEmitterCB);
</script>
Usage
import emitter from 'eventemitter-callback'
emitter.on('event-name', (arg) => {
console.log(arg)
return 'pong'
})
emitter.emit('event-name', 'ping', (arg) => {
console.log(arg)
})
Disable triggering events before listening
By default, the following works normally:
emitter.emit('msg', 1)
emitter.on('msg', (arg) => {
console.log(arg)
})
If this doesn't meet your expectations, you can disable it:
emitter.disablePreEmitter();
emitter.emit('msg', 1)
emitter.on('msg', (arg) => {
console.log(arg)
})
API
on(eventName, listener)
Adds the listener
function to the end of the listeners array for the event named eventName
.
- eventName
string
the name of the event - listener
function
the callback function
The listener
function support AsyncFunction
or returns a Promise
emitter.on('event-name', (arg) => {
console.log(arg)
return new Promise((resolve) => {
resolve('pong')
})
})
emitter.emit('event-name', 'ping', (arg) => {
console.log(arg)
})
once(eventName, listener)
- eventName
string
the name of the event - listener
function
the callback function
Adds a one-time listener
function for the event named eventName
.
emit(eventName[, ...args][, callback])
- eventName
string
the name of the event - ...args
any
- callback
any
the callback function
Returns true
if the event had listeners, false
otherwise.
emitAll(eventName[, ...args])
- eventName
string
the name of the event - ...args
any
Trigger all the listeners at once. Returns a result array by Promise.all
.
emitValidateAll(eventName[, ...args])
- eventName
string
the name of the event - ...args
any
Trigger all the listeners at once and check the values returned.
Returns true
if all listeners returns true, false
otherwise.
emitValidateAnyOf(eventName[, ...args])
- eventName
string
the name of the event - ...args
any
Trigger all the listeners at once and check the values returned.
Returns true
if either listener returns true, false
otherwise.
off(eventName[, listener])
- eventName
string
the name of the event - listener
function
the callback function
Removes the specified listener
from the listener array for the event named eventName
.
Removes all the listeners for the event:
emitter.off('event-name')
emitter._eventEmitter
Reference to current instance of EventEmitter3.
emitter._EventEmitter
Reference to constructor of EventEmitter3.
License
MIT, see the LICENSE file for detail.