监听/发布者模式写出的busbash
let Bus = function() {
this.eventObj = {}
}
Bus.prototype.$on = function(event, fn) {
if (Object.prototype.toString.call(this.eventObj[event]) === '[object Array]') {
this.eventObj[event].push(fn)
} else {
this.eventObj[event] = [fn]
}
}
Bus.prototype.$emit = function(event, data) {
debugger
if (this.eventObj[event] instanceof Array) {
this.eventObj[event].forEach((fn) => {
fn(data)
})
}
}
Bus.prototype.$unload = function(event, fn) {
if (this.eventObj[event] instanceof Array) {
this.eventObj[event].forEach((item, index) => {
if (item === fn) {
this.eventObj[event].splice(index, 1)
}
})
}
}
export default new Bus()
复制代码
使用方法以下ui
import bus from 'bus.js'
function cb() {
...
}
bus.$on('eventName', cb) // 将回调绑定事件
bus.$emit('eventName', data) // 触发事件,传入参数 data,执行回调
bus.$unload('eventName', cb) // 删除 eventName 事件中绑定的回调
复制代码
以为对你有帮助,点个赞可好呀~~this