前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >JS观察者订阅模式

JS观察者订阅模式

原创
作者头像
剁椒鱼鳞
发布2023-05-26 15:27:32
发布2023-05-26 15:27:32
34700
代码可运行
举报
文章被收录于专栏:前端小学生前端小学生
运行总次数:0
代码可运行

以下为Demo:

代码语言:javascript
代码运行次数:0
运行
复制
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) => {
	
})

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档