# event-bus **Repository Path**: source-code-online/event-bus ## Basic Information - **Project Name**: event-bus - **Description**: 基于:happy-event-bus 源码注释、学习 - **Primary Language**: TypeScript - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-11-26 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # event-bus > 该库为源码注释库,用作学习使用,并与[源库](https://github.com/tangdaohai/happy-event-bus)保持更新 [![Github Actions Test](https://github.com/tangdaohai/happy-event-bus/workflows/test%20CI/badge.svg)](https://github.com/tangdaohai/happy-event-bus/actions?query=workflow%3A%22test+CI%22) [![codecov.io](https://codecov.io/gh/tangdaohai/happy-event-bus/branch/master/graph/badge.svg)](https://codecov.io/gh/tangdaohai/happy-event-bus) [![npm version](https://img.shields.io/npm/v/happy-event-bus)](https://www.npmjs.com/package/happy-event-bus) ![file size](https://img.shields.io/bundlephobia/minzip/happy-event-bus?color=rgb%2855%2C%20173%2C%20112%29&label=file%20size) ![license MIT](https://img.shields.io/github/license/tangdaohai/happy-event-bus) Event bus 支持 symbol/string/number. * Typescript * 可以运行在浏览器或Node.js(任何可以运行JavaScript的地方) * 支持多种事件类型(symbol/string/number) * [Easy and quickly cancel listen](#quickly-cancel-listen) > issues: on('xxx', 'uuid', callback); 如果uuid相同,则不会添加进回调列表 ### install ##### npm ```sh npm i happy-event-bus # or yarn add happy-event-bus ``` ##### CDN UMD build ```html ``` ### use ##### init ```ts // 初始化 import Emitter from 'happy-event-bus' const emitter = new Emitter() // or export emitter export default emitter ``` ##### on and emit ```ts 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') // TODO Symbol.for('foo') ``` ##### once ```ts import emitter from './emitter.js' // emit后会自动移除监听 emitter.once('foo') ``` ##### quickly cancel listen on/once 将会返回off方法本身 ```ts 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 ```ts 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](http://opensource.org/licenses/MIT)