最近在寫微信小程序的時候,需要用到全局事件的訂閱裂明,小程序自身沒有該機制椿浓,自己寫了一個,放到app.js上面闽晦,完成了全局事件機制扳碍,代碼如下:
/**
* 全局事件響應(yīng)機制
* 使用方法:
* 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) // 帶有回調(diào)函數(shù)的注銷
*/
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