js实现观察者模式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>面向对象之观察者模式</title>
</head>
<style type="text/css">
       .word{
             width:500px;
             height: 150px;
             border:1px solid #333;
             margin-top:20px;
       }

</style>
<body>
       <h1>用观察者模式来切换</h1>
       <select name=""  id="">
           <option value="default">默认风格</option>    
           <option value="male">男士风格</option>
           <option value="female">女士风格</option>
       </select>
       <input type="button" name="" value="观察动作栏" onclick="t1();">
       <input type="button" name="" value="不观察动作栏" onclick="t2();">
          <div class="word" id="content">内容</div>
          <div class="word" id="ad">广告</div>
          <div class="word" id="study">动作</div>
</body>
<script type="text/javascript">
        var sel =document.getElementsByTagName('select')[0];
        sel.observers={};
        sel.attach=function(key,obj){
            this.observers[key]=obj; 
        }
        sel.detach=function(key){
            delete this.observers[key];
        }
        //追踪监听
        sel.onchange=sel.notify=function(){
            for(var key in  this.observers){
                this.observers[key].update(this);
            }
        }
        //客户端
       var content= document.getElementById('content');
         content.update=function(observee){
              if(observee.value=='male'){
                  this.style.backgroundColor='gray';
              }else if(observee.value=='female'){
                  this.style.backgroundColor='pink';
              }
        }
        var ad= document.getElementById('ad');
         ad.update=function(observee){
              if(observee.value=='male'){
                  this.innerHTML='汽车';
              }else if(observee.value=='female'){
                  this.innerHTML='化妆品';
              }
        }
        //让content观察select的变化
        sel.attach('content',content);
        sel.attach('ad',ad);
        //耦合度低
        var study=document.getElementById('study');
        study.update=function(observee){
            if(observee.value=='male'){
                  this.innerHTML='学习计算机';
            }else if(observee.value=='female'){
                 this.innerHTML='学习美容';
            }
        } 
        sel.attach('study',study);


        function t1(){
            sel.attach('study',study);
        }
        function t2(){
           sel.detach('study');
        }

</script>
</html>

posted @ 2016-08-18 16:29  骏码信息  阅读(224)  评论(0编辑  收藏  举报