用观察者模式

来源:互联网 发布:淘宝客淘口令怎么设置 编辑:程序博客网 时间:2024/05/01 01:18
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>


<h1>用观察者模式来切换</h1>
<select>
   <option value="male">男士风格</option>
   <option value="female">女士风格</option>
</select>
<div id="content" style="width:100px; height: 100px; border:1px solid #000;"></div>
<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 observers[key];
}

sel.onchange=sel.notify=function(){
console.log(this.observers);
for(var key in this.observers){
this.observers[key].update(this);
}
}

//客户端
var content=document.getElementById("content");
content.update=function(obs){
if(obs.value=='male'){
this.style.backgroundColor='gray';
}else if(obs.value='female'){
this.style.backgroundColor='red';
}
}

//让content 观察select 变化
sel.attach('content',content);


</script>


</body>
</html>
0 0