UNPKG

yanan.wang

Version:

This is a toolset

115 lines (93 loc) 2.44 kB
/** *@class * @desc 创建事件中心 * * */ class EventBus{ constructor() { this.events = {} } /** * @method * @desc 订阅事件 * @param {String} eventName 事件类型 * @param {function} fn 回调函数 * @param {object} thisArg this绑定(可选) * */ on(eventName, fn, thisArg) { this.validator(eventName, fn) this.events[eventName] ||= []; let handler = this.events[eventName] handler.push({fn, thisArg}) return this } /** * @method * @desc 发出事件 * @param {String} eventName 事件类型 * @param {any} args 参数列表 * */ emit(eventName, ...args) { this.validator(eventName) this.events[eventName] && this.events[eventName].forEach(({fn, thisArg}) => { fn.apply(thisArg, args) }) return this } /** * @method * @desc 取消事件 * @param {String} eventName 事件类型 * @param {function} fn 订阅的回调 * */ off(eventName, fn) { this.validator(eventName, fn) const handler = this.events[eventName] //pure function let events = [...handler] if (events.length) { const index = events.findIndex(({fn: fun}) => fun === fn) index > -1 && events.splice(index, 1) }else { throw new Error("不存在该事件类型") } if(!events.length) { delete this.events[eventName] } } /** * @method * @desc 取消该事件类型 * @param {String} eventName 事件类型 * */ offAll(eventName) { delete this.events[eventName] } /** * @method * @desc 定义的事件类型,只允许有一个监听函数。 * @param {String} eventName 事件类型 * @param {function} fn 回调函数 * @param {object} thisArg this绑定(可选) * */ once(eventName, fn, thisArg) { this.validator(eventName, fn) const once = (...payload) => { this.off(eventName, fn) fn.apply(payload) } return this.on(eventName, once, thisArg) } //抛出异常的方法 validator(eventName, fn) { if (typeof eventName !== "string") { throw new TypeError("the event name must be string type") } if ( fn && typeof fn !== "function") { throw new TypeError("the event callback must be function type") } } } module.exports = { EventBus }