JS观察者订阅模式

2023-05-26 15:27:32 浏览数 (1)

以下为Demo:

代码语言:javascript复制
class Notice {
    private eventList = {};

    private constructor(appSNC) {
    		this.init(appSNC);
    }
    /* 已通过singleton方法实现单列
    static _ins: any = null;
    static getInstance() {
        if (!this._ins) {
            return this._ins = new Notice();
        }
        return this._ins;
    }
    */
    public init(appSNC) {
        const initFaceSuccess = (res) => {
            // @ts-ignore
            this.trigger('ready', res);
        }
    }
    public listen(key, fn) {
        if (!this.eventList[key]) {
            this.eventList[key] = [];
        }
        this.eventList[key].push(fn);
    }
    private trigger() {
        const key = Array.prototype.shift.call(arguments);
        const fns = this.eventList[key];
        if(!fns || fns.length === 0) {
            return false;
        }
        for(let i = 0, fn; fn = fns[i  ];) {
            fn.apply(this, arguments);
        }
    }
    public remove(key: string, fn: any) {
        const fns = this.eventList[key];
        if(!fns) {
            return;
        }
        if(!fn) {
            fns && (fns.length = 0);
        }
        for(let l = fns.length; l >= 0; l--) {
            let _fn = fns[l];
            if(_fn === fn) {
                fns.splice(l,1);
            }
        }
    }
}
export default singleton(Notice);

const notice = new Notice(appSNC);
notice.listen('ready', (res) => {
	
})

0 人点赞