发布订阅模式

简写发布订阅模式

var publisher={};//定义发布者
publisher.subscribleList=[];//定义订阅者回调函数列表
//增加订阅者的函数
publisher.on=(fn)=>{
    publisher.subscribleList.push(fn);
}
//发布消息的函数
publisher.emit=function(){
    for(const fn of this.subscribleList)
    {
        fn.apply(this,arguments);
    }
}
//订阅方式
publisher.on((a)=>{
    console.log(a);
})
publisher.emit('订阅消息1')
publisher.emit('订阅消息2')
publisher.emit('订阅消息3')

参考

完整发布订阅

let event={
    subscribleList:{},
    track(key,fn)
    {
        if(!this.subscribleList[key])
        {
            this.subscribleList[key]=[]
        }
        this.subscribleList[key].push(fn);
    },
    trigger(key,args)
    {
        let deps=this.subscribleList[key]
        if(!deps)
            return false;
        deps.forEach(fn=>{
            console.log(args);
            fn.apply(this,[args])
        })
    }
}
// 再定义一个installEvent函数,用于给所有对象动态安装发布-订阅功能
// 如:另一家售楼处也想要这个功能,就可以调用这个注册了,不同再写多一次这段代码
let installEvent = obj => {
    for (let i in event) {
        obj[i] = event[i]
    }
}
let salesOffices = {}
installEvent(salesOffices)
salesOffices.track('squareMeter88', (price) => {
    console.log('小明,你看中的88平方的房子,价格=' + price)
})
// 小光订阅信息
salesOffices.track('squareMeter88', price => {
    console.log('小光,你看中的88平方的房子,价格=' + price)
})
// 小红订阅信息
salesOffices.track('squareMeter100', price => {
    console.log('小红,你看中的100平方的房子,价格=' + price)
})
salesOffices.trigger('squareMeter88', 2000000)
salesOffices.trigger('squareMeter100', 2500000)

vue中的发布订阅

let activeEffect;
//为了在调用depend()的时候把相关函数作为订阅者
//添加到subscribers中去,以后notify的时候就可以用了
class Dep{
    constructor(value)
    {
        this.subscribers=new Set();///所有的订阅者
        this._value=value;
    }
    get value()
    {
        this.depend();
        return this._value
    }
    set value(newVal)
    {
        this._value=newVal;
        this.notify();
    }
    depend()
    {
        if(activeEffect)
        {
            this.subscribers.add(activeEffect)
        }
    }
    notify(){
        //通知订阅者
        this.subscribers.forEach(effect=>{
            effect();
        })
    }
}
function watchEffect(effect)
{
    activeEffect=effect;
    effect();
    activeEffect=null;
}
const dep = new Dep('test');
//如何将一个dep与一个值相关联
//在Dep的构造函数中加一个value属性,通知的时候使用value就好了
watchEffect(()=>{
    console.log(dep.value)
})
dep.value='changed'
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值