模拟实现Event事件订阅、发布机制

2019-04-10  本文已影响0人  原来如此scater

最近在写微信小程序的时候,需要用到全局事件的订阅,小程序自身没有该机制,自己写了一个,放到app.js上面,完成了全局事件机制,代码如下:

/**
 * 全局事件响应机制
 * 使用方法:
 *    1、事件订阅:app.event.on(eventName, this, callback)
 *    2、事件广播:app.event.emit(eventName, params)
 *    3、事件注销:app.event.off() // 注销全部
                app.event.off(eventName) // 注销具体事件
                app.event.off(eventName, callback) // 带有回调函数的注销
 */

class Event {
  on (event, ctx, callback) {
      if (typeof callback != "function") {
          console.error('callback must be a function')
          return
      }
      this._stores = this._stores || {};
      (this._stores[event] = this._stores[event] || []).push({cb: callback, ctx: ctx})
  }
  emit (event) {
      this._stores = this._stores || {}
      let store = this._stores[event], args
      if (store) {
          store = store.slice(0)
          args = [].slice.call(arguments, 1)
          for (var i = 0, len = store.length; i < len; i++) {
              store[i].cb.apply(store[i].ctx, args)
          }
      }
  }
  off (event, callback) {
      this._stores = this._stores || {}
      // all
      if (!arguments.length) {
          this._stores = {}
          return
      }
      // specific event
      var store = this._stores[event]
      if (!store) return
      // remove all handlers
      if (arguments.length === 1) {
          delete this._stores[event]
          return 
      }
      // remove specific handler
      var cb
      for (var i = 0, len = store.length; i < len; i++) {
          cb = store[i].cb
          if (cb === callback) {
              store.splice(i, 1)
              break
          }
      }
      return
  }   
}

module.exports = Event

上一篇 下一篇

猜你喜欢

热点阅读