发布订阅

  有一说一,发布订阅有点简单,随随便便就能想到思路,就是on的时候将对应名字的callback存到对应名字的数组中,emit的时候将数组中的所有function都执行一边,然后off的时候将指定事件名下数组中指定的function删了就好。
  这里提一下观察者模式,之前单纯的感觉两者差不多,后来看了一些东西知道其实还是有一点区别的。发布订阅的话,emit可以被任何东西调用,也就是说具体的发布者和接收者中间隔了层eventHub(大家喊他调度中心),而观察者则是订阅者(observable)直接订阅发布者,中间少了个调度。嘛,具体功能上面其实还是差不太多。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 发布订阅
const EventHub = {
eventList:{},
on(eventName,fn){
if(!this.eventList[name]){
this.eventList[name] = []
}
this.eventList[name].push(fn);
},
emit(name){
this.eventList[name].forEach(fn => fn())
},
off(name,fn){
const index = indexOf(this.eventList[name],fn)//
if(index === -1) return false;
this.eventList[name].splice(index,1);
}
}
const indexOf = (array,target)=>{
if (arrray === undefined) return -1;
return array.indexOf(target);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 观察者
const Observable={
subjectList=[];

subscribe(fn){
this.subjectList.push(fn);
}

unSubscribe(fn){
const index = indexOf(subjectList,fn)//
if(index === -1) return false;
subjectList.splice(index,1);
}
notify(...args){
this.subjectList.forEach((fn) =>{
fn(...args)
})
}
}