以下为监听方法
class Event {
on(event, fn, ctx) {
if (typeof fn != "function") {
console.error('fn must be a function')
return
}
this._stores = this._stores || {};
(this._stores[event] = this._stores[event] || []).push({
cb: fn,
ctx: ctx
})
}
emit(event) {
this._stores = this._stores || {}
var 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, fn, ctx) {
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 (store[i].ctx === ctx) {
store.splice(i, 1)
break
}
}
return
}
}
module.exports = {
Event
}
以下为使用方法
将events挂到全局对象上
wx.event = new Event();
监听开始,其中“监听名称”为需要监听的名称,可以用于多个地方监听;监听标识作用于卸载监听的唯一标识(全局唯一),如果不传监听标识,默认卸载的监听为第一个监听函数,出现多个相同“监听名称”会出现卸载错误的监听函数。
wx.event.on('监听名称', function (res) {
//得到监听结果,执行函数操作
},'监听标识');
卸载监听
wx.event.off("监听名称","监听标识");
触发监听函数,object为监听函数接收到的内容
wx.event.emit('监听名称', object);