发布订阅简单实现

68 阅读1分钟
function Event() {
    this.events = {}
}
Event.prototype.on = function(key, fn) {
    if (!this.events) { // 继承的元素上没有events
        this.events = {}
    }
    this.events[key] = this.events[key] || []
    this.events[key].push(fn)
}
Event.prototype.emit = function(key, ...args) {
    let fns = this.events[key] || []
    fns.forEach(fn => {
        fn(...args)
    });
}
Event.prototype.off = function(key, cb) {
    let fns = this.events[key] || []
    if (fns.length) {
        this.events[key] = fns.filter(fn=>fn !== cb && fn.l !== cb) // 有一个相等就不行
    }
}
Event.prototype.once = function(key, cb) {
    // on/off不能放在once阶段,要放在emit阶段,放进去的数据内容是once
    let once = (...args) => {
        cb(...args)
        this.off(key, once)
    }
    once.l = cb
    this.on(key, once)
}
let parent = new Event()
let fn1 = (...args) => {
    console.log(1, ...args)
}
let fn2 = (...args) => {
    console.log(2, ...args)
}
parent.once('action', fn1)
parent.once('action', fn2) // [{action: [fn1, fn2]}]
// parent.off('action', fn1)
parent.emit('action', 11, 22)
parent.emit('action', 11, 22)