react eventbus 監(jiān)聽事件

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() {
    /**
     * 構造函數(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ù)組存入對應的鍵名下
  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;


?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容