基本觀察者模式
以下Observer為觀察者使碾,當(dāng)state改變時(shí)通知觀察者底洗。addObserver進(jìn)行訂閱,this.observers中儲(chǔ)存了所有的觀察者智蝠。notify時(shí)對(duì)觀察者進(jìn)行通知腾么。
class Subject{
constructor(){
this.state="init"
this.observers=[]
}
setState(state){//修改狀態(tài)并通知觀察者
this.state=state
this.notify(state)
}
notify(state){//通知
this.observers.forEach(observer=>observer.getNewState(state))
}
addObserver(observer){//訂閱
this.observers.push(observer)
}
}
class Observer{
getNewState(state){
console.log(`new state is: ${state}`)
}
}
const sub=new Subject()
const observer1=new Observer()
const observer2=new Observer()
sub.addObserver(observer1)//new state is: next state
sub.addObserver(observer2)//new state is: next state
sub.setState("next state")
node中EventEmitter模塊實(shí)現(xiàn)
參考: 循序漸進(jìn)教你實(shí)現(xiàn)一個(gè)完整的node的EventEmitter模塊
EventEmitter的使用方式:
.on(type,function)設(shè)置監(jiān)聽事件的名稱,.emit(type,args)觸發(fā)事件杈湾,傳遞參數(shù)
var events=require('events');
var eventEmitter=new events.EventEmitter();
eventEmitter.on('say',function(name){
console.log('Hello',name);
})
eventEmitter.emit('say','Jony yu');
EventEmitter的基本實(shí)現(xiàn):handler儲(chǔ)存所有的事件解虱,key為事件名稱。value為數(shù)組漆撞,數(shù)組中儲(chǔ)存監(jiān)聽的function
handler:{
click:[],
change:[]
}
class EventEmitter{
constructor(){
this.handler={}
}
on(type,fn){
//第一次添加對(duì)應(yīng)type-初始化
!this.handler[type]&&(this.handler[type]=[])
this.handler[type].push(fn)
}
emit(type,args){
if(!this.handler[type])
{
console.log(`did not add listener : ${type}`)
return null
}else {
this.handler[type].forEach(fn=>fn(args))
}
}
}
let event=new EventEmitter();
event.on('say',function(str){
console.log(str);
});
event.emit('say','hello Jony yu');