import { EmitFunc, ListenerFunc } from "../notice";
export class EventBus {
public static getInstance: () => EventBus;
public static instance: EventBus;
public events: any;
public emit: EmitFunc;
public addListener: ListenerFunc;
public removeListener: ListenerFunc;
constructor() {
/**
* 構(gòu)造函數(shù)需要存儲的 event 事件
*/
this.events = this.events || new Object();
}
}
EventBus.getInstance = function () {
if (!this.instance) {
this.instance = new EventBus();
}
return this.instance;
}
/**
* @name emit
* @description 觸發(fā)事件
* @param {*} type 事件類型
* @param {...any} args 參數(shù)
*/
EventBus.prototype.emit = function (type: any, ...args: any) {
const eventFuncs = this.events[type];
// 查看這個 type 的 event 有多少個回調(diào)函數(shù),如果有多個需要依次調(diào)用。
if (Array.isArray(eventFuncs)) {
// tslint:disable-next-line: prefer-for-of
for (let index = 0; index < eventFuncs.length; index++) {
eventFuncs[index].apply(this, args)
}
} else if (eventFuncs == null) {
console.warn(`eventBus 沒有監(jiān)聽${type}事件卻發(fā)送了事件`)
} else {
eventFuncs.apply(this, args)
}
};
/**
* @name addEventListener
* @description 增加監(jiān)聽函數(shù)
* @param {*} type
* @param {*} fun
*/
EventBus.prototype.addListener = function (type: any, func: any) {
const eventFuncs = this.events[type];
// 如果從未注冊過監(jiān)聽函數(shù),則將函數(shù)放入數(shù)組存入對應(yīng)的鍵名下
if (!eventFuncs) {
this.events[type] = [func]
}
// 如果注冊過,則直接放入
else {
eventFuncs.push(func)
}
}
/**
* @name removeListener
* @description 刪除監(jiān)聽事件
* @param {*} type
*/
EventBus.prototype.removeListener = function (type: any, func: any) {
if (this.events[type]) {
const eventFuncs = this.events[type]
if (Array.isArray(eventFuncs)) {
if (func) {
const funcIndex = eventFuncs.findIndex(eventFunc => func === eventFunc)
if (funcIndex !== -1) {
eventFuncs.splice(funcIndex, 1)
} else {
console.warn(`eventBus may remove unexit func(${type})`)
}
} else {
delete eventFuncs[type]
}
} else {
delete eventFuncs[type]
}
}
}
notice 文件
import { GetOrderDetailResponse } from "src-root/services/dto/dto-cart-order";
import { BillCalculateResponse } from "src-root/services/dto/dto-settle-calculate";
export interface IAPI {
/**
* 刷新購物車
*/
refreshShoppingCart?: GetOrderDetailResponse;
/**
* 刷新賬單
*/
refreshBill?: BillCalculateResponse;
/**
* 刷新開瓶數(shù)
*/
refreshBottle?: any;
}
export type EmitFunc = <key extends keyof IAPI>(command: key, options?: IAPI[key]) => void;
export type ListenerFunc = <key extends keyof IAPI>(command: key, callback?: (msg?: IAPI[key]) => void) => void;