Event bus util and support symbol/string/number.
- Typescript
- Can be run in a browser or Node.js(works in any JavaScript runtime)
- Support multiple event types(symbol/string/number)
- Easy and quickly cancel listen
npm i happy-event-bus
# or
yarn add happy-event-bus
UMD build
<script src="https://unpkg.com/happy-event-bus/dist/index.umd.js"></script>
// import and init
import Emitter from 'happy-event-bus'
const emitter = new Emitter()
// or export emitter
export default emitter
import emitter from './emitter.js'
// string
emitter.on('anyone', (...item) => { console.log(item) })
emitter.emit('anyone', 'foo') // -> ['foo']
emitter.emit('anyone', 'foo', 'bar') // ['foo', 'bar']
// number
const ONE = 1
emitter.on(ONE, () => {})
emitter.emit(ONE)
// symbol
const foo = Symbol('foo')
emitter.on(foo, (item) => { console.log(item) }) // -> foo
emitter.emit(foo, 'foo')
import emitter from './emitter.js'
// remove auto after emit
emitter.once('foo')
on/once will return a function and can be off himself
import emitter from './emitter.js'
const cb = () => {}
const fooListenStopHandle = emitter.on('foo', cb)
// off
fooListenStopHandle()
emitter.emit('foo') // -> foo cb never call
const barCb = () => {}
const barListenStopHandle = emitter.once('bar', barCb)
// off
barListenStopHandle()
emitter.emit('bar') // -> bar cb never call
import emitter from './emitter.js'
// off callback
const cb = () => {}
emitter.on('foo', cb)
emitter.off('foo', cb)
// off foo callback
emitter.off('foo')
// off all item
emitter.off()
Copyright (c) 2020 唐道海