js 观察者模式

观察者模式的封装

const event = {
    RESPONSE: "Response",
    EVENT_PUSH: 'event_push',
}

class EventManagers {
    static getInstance() {
        if (!this.instance) {
            this.instance = new EventManagers();
        }
        return this.instance;
    }
    constructor() {
        this._eventListeners = Object.create(null); // 定义事件的存储对象
    }
    //添加事件监听
    addListener(eventName, callBack, isOnceCB = false) {
        if (typeof callBack !== "function") {
            throw new TypeError("The callBack must be a function!");
        }
        if (!this._eventListeners[eventName]) {
            this._eventListeners[eventName] = [];
            this._eventListeners[eventName].push({
                callBack,
                isOnceCB
            });
        } else {
            this._eventListeners[eventName].push({
                callBack,
                isOnceCB
            }); // 存入监听的事件名和事件
        }
    }

    //一次性事件监听
    once(eventName, callBack) {
        this.addListener(eventName, callBack, true);
    }

    // 事件触发
    emitEvent(eventName, ...args) {
        if (!this._eventListeners[eventName]) {
            return false;
        }
        const len = this._eventListeners[eventName].length;
        for (let i = 0; i < len; i++) {
            let event = this._eventListeners[eventName][i];
            event.callBack.call(this, ...args);
            if (event.isOnceCB) {
                this.removeListener(eventName, event.callBack);
                i--;
            }
        }
    }
    // 移除监听事件
    removeListener(eventName, callBack) {
        if (!this._eventListeners[eventName]) return this;
        if (!callBack) {
            delete this._eventListeners[eventName];
            return this;
        } else {
            this._eventListeners[eventName].forEach((item, index) => {
                if (item.callBack === callBack) {
                    this._eventListeners[eventName].splice(index, 1);
                } else {
                    return this;
                }
            });
        }
    }
    // off:removeListener 的别名
    off(eventName, callBack) {
        this.removeListener(eventName, callBack);
    }
    // 移除所有监听事件
    clearAllListener(eventName) {
        if (eventName) {
            if (this._eventListeners[eventName]) {
                this._eventListeners[eventName].length = 0;
            }
        } else {
            this._eventListeners = Object.create(null);
        }
    }
}


const EventManager = {
    eventUtil: EventManagers.getInstance(),
    event: event
}

export default EventManager

你可能感兴趣的:(js 观察者模式)