arbitrary-emitter
Event emitter with ES6 Map sugar for modern browsers and node.js (~450 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 (~450 bytes when gzipped)
- blazing fast
- conventional api (
on
, off
, once
and emit
)
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 key = {}
emitter.on(key, () => doSomething())
emitter.emit(key)
Emitter API
on(eventKey, listener)
Adds the listener
function to the end of the listeners array for the event tagged with eventKey
. eventKey
can be any type of value. A check is made to see if the listener has already been added so it won't be called multiple times. Event listeners are invoked in the order they are added.
const key = {}
emitter.on(key, () => doSomething())
emitter.emit(key)
once(eventKey, listener)
Same as on
, but listener
will be triggered just one time, then it will be removed.
const key = {}
emitter.once(key, () => doSomethingOnce())
emitter.emit(key)
emitter.emit(key)
emit(eventKey[, options])
Synchronously calls each of the listeners registered for the event tagged with eventKey
, passing the supplied argument options
to each
emitter.on('test', (opts) => console.log(opts.test))
const options = { test: 'Testing!' }
emitter.emit('test', options)
off([eventKey[, listener]])
- When no argument is passed all the listeners and its eventKeys will be removed from the emitter
- If an
eventKey
but no listener
is passed all the listeners and its key will be removed - If
eventKey
and listener
are passed as arguments just the listener will be removed from its group
emitter.off(key, action)
emitter.off(key)
emitter.off()
listeners(eventKey)
Returns a copy of the array of listeners for the event tagged eventKey
const key = {}
const f1 = () => console.log('f1')
const f2 = () => console.log('f2')
emitter.on(key, f1)
emitter.on(key, f2)
emitter.listeners(key)[0] === f1
emitter.listeners(key)[1] === f2
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