設計模式之觀察者模式

<html>
  <head>
    <title>Observer</title>
    <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
  </head>
  <body>
    <input type="text" id="ipt"/>
    <button id="btn">點擊</button>


    <script type="text/javascript">
      function ObserverList(){
        this.observerList = [];
      }

      ObserverList.prototype.add = function(observer){
        return this.observerList.push(observer);
      }

      //統計觀察者列表中的觀察者數量
      ObserverList.prototype.count = function() {
        return this.observerList.length;
      };
      //根據序號獲取觀察者對象
      ObserverList.prototype.get = function(index) {
        if (index >= 0 && index < this.observerList.length) {
          return this.observerList[index];
        }
      };



      function Subject(){
        this.observers =  new ObserverList();
      }

      Subject.prototype.addObserver = function(observer){
         return this.observers.add(observer);
      }
      Subject.prototype.notify = function(context){
        var observerCount = this.observers.count();
        for (var i = 0; i < observerCount; i++) {
          this.observers.get(i).update(context);
        }
      }


      function Observer() {
        this.update = function(context) {
          console.log(context);
        };
      }


      function extend(obj, extension) {
        for (var key in extension) {
          obj[key] = extension[key];
        }
      }


      $btn = $("#btn");
      $ipt = $("#ipt");
      extend($btn,new Subject());
      $btn.click(function(){
        var a= this;debugger;
        $btn.notify($ipt.val());
      });

      var  a1= new Observer();
      a1.update = function(context){
        console.log("a1 observer"+context);
      }
      $btn.addObserver(a1);
      var  a2= new Observer();
      $btn.addObserver(a2);
    </script>
  </body>
</html>

發佈了45 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章