用js写的简单观察者模式

<span style="font-size:14px;"><html>
	<head>
	<meta Content-type="text/html" charset="utf-8"></meta>	

	</head>
	<body>
		<select name="change">
			<option value="red">红色</option>	
			<option value="yellow">黄色</option>
		</select>

		<div id="color" style="width:300px;height: 300px">红色</div>
		<div id="text" style="width:300px;height: 300px">文字显示</div>

	</body>
	<script type="text/javascript">
		var sel = document.getElementsByTagName("select")[0];
		 sel.observers = {};
		//添加观察者
		sel.attach = function(key,obj){
			sel.observers[key] = obj;
		}
		//删除观察者
		sel.detach = function(key){
			delete sel.observers[key]
		}
		//被观察者改变是通知观察者
		sel.onchange = sel.notify = function(){
			for(var key in sel.observers){
				sel.observers[key].update(sel);
			}
		}
		//颜色观察者得到通知的动作
		document.getElementById("color").update = function(observer){
			if(observer.value == "red"){
				this.style.backgroundColor = "red";
			}else if(observer.value == "yellow"){
				this.style.backgroundColor = "yellow";
			}
		}
		//文字观察者得到通知后的动作
		document.getElementById("text").update = function(observer){
			if(observer.value =="red"){
				this.innerHTML = "我喜欢红色";
			}else if(observer.value = "黄色"){
				this.innerHTML = "我喜欢黄色";
			}
		}


		var color = document.getElementById("color");
		var text = document.getElementById("text");
		sel.attach("color",color);
		sel.attach("text",text);
 	</script>
</html></span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值