Simple and tiny event emitter library for JavaScript.
- No Node.js EventEmitter compatibility.
- Only 119 bytes (minified and gzipped). It uses Size Limit to control size.
on
method returnsunbind
function. You don’t need to save callback to variable forremoveListener
.- No aliases, just
emit
andon
methods.
import NanoEvents from 'nanoevents'
const emitter = new NanoEvents()
const unbind = emitter.on('tick', volume => {
summary += volume
})
function disable () {
unbind()
}
Because main Nano Events API has only 2 methods, you could just create proxy methods in your class:
class Ticker {
constructor() {
this.emitter = new NanoEvents()
}
on() {
return this.emitter.on.apply(this.events, arguments)
}
tick() {
this.emitter.emit('tick')
}
}
Use on
method to add listener for specific event:
emitter.on('tick', number => {
console.log(number)
})
emitter.emit('tick', 1)
// Prints "1"
emitter.emit('tick', 2)
// Prints "2"
Methods on
returns unbind
function. Call it and this listener
will be removed from event.
const unbind = emitter.on('tick', number => {
console.log('on ' + number)
})
emitter.emit('tick', 1)
// Prints "on 1"
unbind()
emitter.emit('tick', 2)
// Prints nothing
Method emit
will execute all listeners. First argument is event name, others
will be passed to listeners.
emitter.on('tick', (a, b) => {
console.log(a, b)
})
emitter.emit('tick', 1, 'one')
// Prints 1, 'one'
You can get used events list by events
property.
const unbind = emitter.on('tick', () => { })
Object.keys(emitter.events) //=> ["tick"]
unbind()
Object.keys(emitter.events) //=> []
unbindAll
method will remove all listeners to all events.
import unbindAll from 'nanoevents/unbind-all';
emitter.on('event1', () => { })
emitter.on('event2', () => { })
unbindAll(emitter);
Object.keys(emitter.events) //=> { }