实现一个发布-订阅模式

本文介绍了订阅/发布者模式,这是一种一对多的关系,允许多个观察者监听同一个主题对象。当主题状态变化时,会通过调度中心通知所有观察者。文章探讨了如何在JavaScript中实现这种模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

订阅/发布者模式
订阅发布模式:一对多的关系,让多个观察者同时监听某一个主题对象,这个主题对象的状态发生改变时就会通知所有观察者对象,中间通过一个调度中心来发布通知

function Dep(){
    this.subs = [];
}

Dep.prototype.addSub = function(sub){
    this.subs.push(sub);
}
Dep.prototype.notify = function(){
    this.subs.forEach(sub => sub.update())
}

function load1 (){}
load1.prototype.update = function(){
    console.log('load1')
}

function load2 (){}
load2.prototype.update = function(){
    console.log('load2')
}

var dep = new Dep();
var watcher1 = new load1()
var watcher2 = new load2()
dep.addSub(watcher1)
dep.addSub(watcher2)
dep.notify();
// https://www.cnblogs.com/suyuanli/p/9655699.html
class Event{
    constructor(){
        handlers = {};
    }

    on(type, handler){
        if (!(type in this.handlers)) {
            this.handlers[type] = [];
        }
        this.handlers[type].push(handler);
    }

    emit(type, ...params){
        if (!(type in this.handlers)) {
            return new Error('未注册!')
        }

        this.handlers[type].forEach(handler => {
            handler(...params);
        });
    }

    // 移除
    remove(type, handler){
        if (!(type in this.handlers)) {
            return new Error('无效事件');
        }

        if (!handler) { // 没有指明handler,移除type
            delete this.handlers[type];
        } else {
            const idx = this.handlers[type].findIndex(ele => ele === handler);
            if (idx === undefined) {
                return new Error('no')
            }
            this.handlers[type].splice(idx, 1);
            if (this.handlers[type].length === 0) {
                delete this.handlers[type];
            }
        }
    }
}

function load(params){
    console.log('load', params)
}

function foo(params){
    console.log('foo...', params)
}

var event = new Event();
event.on('load', load);
event.on('load', foo);

// 触发
event.emit('load', 'load触发')

// 移除foo
event.remove('load', foo);
event.emit('load')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值