arbitrary-emitter
Event emitter with Map/Set sugar for modern browsers and node.js (~500 bytes). arbitrary-emitter.jacoborus.codes
arbitrary-emitter stores listeners and actions in Maps, this allows to use arbitrary values as keys for your listeners.
It's written in vanilla ES6, so you will have to transpile it before using it in old browsers or node.js < v5.9
Features
- works in browsers and node.js
- allows to use arbitrary values as keys for listeners
- really small footprint (~500 bytes when gzipped)
- blazing fast
- conventional api (
on
, off
, once
and emit
) on
method returns an unsubscription function (like in redux.js)
Usage
Install with npm, clone the repo or download and extract the zip. Then import or insert it as script tag.
const emitter = arbitraryEmitter()
const obj = {}
emitter.on(obj, () => doSomething())
emitter.emit(obj)
Emitter API
on(key, action)
Adds the listener action
to the Set
for the event tagged with key
.
key
can be any type of value.
on
returns removeListener method
const obj = {}
let removeListener = emitter.on(obj, () => doSomething())
emitter.emit(obj)
emitter.emit(obj)
removeListener()
emitter.emit(obj)
once(key, action)
Adds the listener action
to the Set
for the event tagged with key
. action
will be triggered just one time, then it will be removed.
key
can be any type of value
const obj = {}
emitter.once(obj, () => doSomethingOnce())
emitter.emit(obj)
emitter.emit(obj)
emit(key[, ...args])
Synchronously calls each of the listeners registered for the event tagged with key
, and pass the rest of the arguments to them
emitter.on('test', (a, b) => console.log(a + b))
emitter.emit('test', 1, 2)
trigger(key[, args])
Synchronously calls each of the listeners registered for the event tagged with key
, and pass args
array as arguments to them
emitter.on('test', (a, b) => console.log(a + b))
emitter.trigger('test', [1, 2])
off(key[, action])
Remove action
from listeners tagged with key
. If no action
is specified will remove all listeners tagged with key
emitter.off(key, action)
emitter.off(key)
Testing
Node
npm test
Browser
Build browser tests (npm run build-tests
) and open test/test.html
Building
- Build UMD file:
npm run build-umd
- Build browser tests:
npm run build-tests
- Run both builds:
npm run build
© 2016 Jacobo Tabernero - Released under MIT License