node中发布订阅(模式)

亿奇学

关注

阅读 45

2021-09-23

function EventEmitter(params) {
    this._events = {}
}

//订阅
EventEmitter.prototype.on = function (eventName, callback) {
    if (!this._events) {
        this._events = {}
    }
    if (this._events[eventName]) {
        this._events[eventName].push(callback);
    } else {
        this._events[eventName] = [callback];
    }
}

//发布
EventEmitter.prototype.emit = function (eventName, ...arg) {
    this._events[eventName].forEach(fn => {
        fn(...arg);
    });
}

//解绑事件
EventEmitter.prototype.off = function (eventName, callback) {
    if (this._events && this._events[eventName]) {
        this._events[eventName].filter(fn => {
            return (fn[eventName] !== callback && fn.l == callback)
        });
    }
}

// 只触发一次
EventEmitter.prototype.once = (eventName, callback) => {
    let one = this.on(eventName, () => {//绑定执行完毕后移除
        callback();
        one.l = callback;
        this.off(eventName, one)
    })
    this.on(eventName, on);
}

module.exports = EventEmitter;

精彩评论(0)

0 0 举报