自定义vue框架之监听器设计方法

监听器设计方法就是一个数值或状态改变可以通知多个观察者,实现改变一个就可以改变多个观察者的功能

<!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>

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值