Package Exports
- nanoevents
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (nanoevents) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Nano Events
Small and simple events API.
- No node.js EventEmitter compatibility.
- Only 447 bytes (minified and gzipped).
onandoncemethods returnunbindfunction. You don’t need to save callback to variable forremoveListener.- No aliases, just
emit,on,oncemethods.
import NanoEvents from 'nanoevents'
const emitter = new NanoEvents()
const unbind = emitter.on('tick', volume => {
summary += volume
})
emitter.once('tick', () => {
works = true
})
function disable () {
unbind()
}Usage
Mixing to Object
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)
}
once() {
return this.emitter.once.apply(this.events, arguments)
}
tick() {
this.emitter.emit('tick')
}
}Add Listener
There are 2 methods to add listener for specific event:
on and one-time once.
emitter.on('tick', number => {
console.log('on ' + number)
})
emitter.once('tick', number => {
console.log('once ' + number)
})
emitter.emit('tick', 1)
// Prints "on 1" and "once 1"
emitter.emit('tick', 2)
// Prints "on 2"Remove Listener
Methods on and once return 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 nothingExecute Listeners
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'Events List
You can get used events list by events property.
const unbind = emitter.on('tick', () => { })
Object.keys(emitter.events) //=> ["tick"]
unbind()
Object.keys(emitter.events) //=> []