Skip to content

tangdaohai/happy-event-bus

Repository files navigation

happy-event-bus

Github Actions Test codecov.io npm version file size license MIT

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

install

npm
npm i happy-event-bus

# or

yarn add happy-event-bus
CDN

UMD build

<script src="https://unpkg.com/happy-event-bus/dist/index.umd.js"></script>

use

init
// import and init
import Emitter from 'happy-event-bus'
const emitter = new Emitter()
// or export emitter
export default emitter
on and emit
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')
once
import emitter from './emitter.js'
// remove auto after emit
emitter.once('foo')
quickly cancel listen

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
off
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()

LICENSE

MIT

Copyright (c) 2020 唐道海

About

event bus util and support symbol/string/number.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published