Skip to content

Instantly share code, notes, and snippets.

@ruter
Last active October 31, 2018 02:17
Show Gist options
  • Save ruter/eae45ee20463b54876a9cd9f6787029a to your computer and use it in GitHub Desktop.
Save ruter/eae45ee20463b54876a9cd9f6787029a to your computer and use it in GitHub Desktop.
可用于小程序的发布订阅模式,主要用于跨页面通讯
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) {
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 === fn) {
store.splice(i, 1)
break
}
}
return
}
}
/**
* 使用示例
* /
// app.js
const Event = require('./utils/event')
App({
event: new Event(),
...
})
// subsPage.js
let app = getApp()
Page({
onLoad: function(){
app.event.on('eventName',this.triggerEvent, this)
},
onUnload: function(){
// remove all
// app.event.off()
// remove all callbacks
app.event.off('eventName')
// remove specific callbacks
// app.event.off('eventName', this.triggerEvent)
},
triggerEvent: function(args) {
...
},
...
})
// emitPage.js
let app = getApp()
Page({
emitFunc: function() {
...
app.event.emit('eventName', arg)
},
...
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment