监听器设计方法就是一个数值或状态改变可以通知多个观察者,实现改变一个就可以改变多个观察者的功能
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
function Subject(){
this.watchers=[];
this.a=1;
}
Subject.prototype={
//将观察者对象添加到观察者数组中
subscribe:function(watcher){
this.watchers.push(watcher);
},
将观察者对象从观察者数组中删除
unsubscrbe:function(watcher){
const index=this.watchers.indexOf(watcher);
if(index>-1){
this.watchers.splice(index,1);
}
},
//通知观察者改变数值
notify:function(){
this.a++;
this.watchers.forEach(watcher=>{
watcher.update(this.a);
});
}
}
function Watcher(name){
this.name=name;
}
Watcher.prototype={
//调用观察者中的更新方法
update:function(num){
console.log(`观察者:${this.name}被通知了,新值为:${num}`);
}
};
//测试案例
const subject=new Subject();
const w1=new Watcher('w1');
const w2=new Watcher('w2');
const w3=new Watcher('w3');
subject.subscribe(w1);
subject.subscribe(w2);
subject.subscribe(w3);
subject.unsubscrbe(w3);
subject.notify();
</script>
</body>
</html>