UNPKG

mini-program-event-store

Version:

A small responsive system suitable for handling data responsive issues in mini program development

133 lines (113 loc) 3.6 kB
class EventBus { constructor() { this.eventBus = {}; } /** * * @param {事件名} eventName * @param {事件回调函数} eventCallback * @param {绑定this} thisArg * @returns this */ on(eventName, eventCallback, thisArg) { if (typeof eventName !== "string") { throw new TypeError("the event name must be string type"); } if (typeof eventCallback !== "function") { throw new TypeError("the event callback must be function type"); } /** * 将事件命收集起来,比如: * eventBus= { why: [{eventCallback, thisArg}] } */ let handlers = this.eventBus[eventName]; if (!handlers) { handlers = []; this.eventBus[eventName] = handlers; } handlers.push({ eventCallback, thisArg, }); /** * 返回 this 是为了支持链式调用 * eventBus.on('event1', callback1) * .on('event2', callback2) * .once('event3', callback3); * */ return this; } once(eventName, eventCallback, thisArg) { if (typeof eventName !== "string") { throw new TypeError("the event name must be string type"); } if (typeof eventCallback !== "function") { throw new TypeError("the event callback must be function type"); } // 创建一个新的回调函数 tempCallback,当接收到emit时,传给 原始的 eventCallback const tempCallback = (...payload) => { // 先把自己 的回调函数 移除 this.off(eventName, tempCallback); // 然后执行原始的 eventCallback,将数据传回去 eventCallback.apply(thisArg, payload); }; return this.on(eventName, tempCallback, thisArg); } /** * * @param {事件名} eventName * @param {参数载荷} payload * @returns this * * 在eventBus中查找对应的事件名,如果存在,则执行对应的回调函数 */ emit(eventName, ...payload) { if (typeof eventName !== "string") { throw new TypeError("the event name must be string type"); } const handlers = this.eventBus[eventName] || []; handlers.forEach((handler) => { handler.eventCallback.apply(handler.thisArg, payload); }); return this; } /** * * @param {要取消监听的事件名} eventName * @param {回调函数} eventCallback */ off(eventName, eventCallback) { if (typeof eventName !== "string") { throw new TypeError("the event name must be string type"); } if (typeof eventCallback !== "function") { throw new TypeError("the event callback must be function type"); } // eventBus= { why: [ {callback1, thisArg}, {callback2, thisArg}], {callback3, thisArg}] } // 找到对应的 回调函数数组 const handlers = this.eventBus[eventName]; if (handlers && eventCallback) { const newHandlers = [...handlers]; for (let i = 0; i < newHandlers.length; i++) { const handler = newHandlers[i]; if (handler.eventCallback === eventCallback) { // 将取消监听的回调函数 删除 const index = handlers.indexOf(handler); handlers.splice(index, 1); } } } if (handlers.length === 0) { delete this.eventBus[eventName]; } } clear() { this.emitBus = {}; } // 检查是否存在指定名称的事件 hasEvent(eventName) { return Object.keys(this.emitBus).includes(eventName); } } export { EventBus };