如何为微信小程序添加事件钩子监听功能?
当触发某个事件后,可以执行挂载到这个事件下的所有操作,并可以取消监听。
class Event {
on(event, fn) {
if (typeof fn != "function") {
console.error('fn must be a function')
return
}
this._stores = this._stores || {}
; (this._stores[event] = this._stores[event] || []).push(fn)
}
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].apply(null, args)
}
}
}
off(event, fn) {
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]
if (cb === fn || cb.fn === fn) {
store.splice(i, 1)
break
}
}
return
}
}
module.exports = {
Event
}
import {Event} from '/utils/event.js'
wx.event = new Event();
var addfun = function(x,y){
return x+y;
}
wx.event.on('change',addfun)
var sum = wx.event.emit('change',x,y);
wx.event.off('change',addfun)
代码出处:qingdian