简写发布订阅模式
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'
3217

被折叠的 条评论
为什么被折叠?



