zoukankan      html  css  js  c++  java
  • 观察者+js 模式

    <script language="JavaScript">
    <!--
    /*---------------------------
        defined observer
    ----------------------------*/
    function Observer()//观察者
    {
       
    }
    Observer.prototype.update = function(context)//观察者方法
    {
        alert(context);
    }
     
    function ConcreteObserver()//具体观察者
    {
        Observer.call(this);
    }

    ConcreteObserver.prototype.update = function(context)//具体观察者方法
    {
        alert("ConcreteObserver response " + context);
    }

    /*---------------------------
        defined ObserverCollection // 观察者集合
    ----------------------------*/
    function ObserverCollection()// 观察者集合
    {
        this._observers_ = new Array();  //定义数组
    }
    ObserverCollection.prototype.add = function(observer)  //定义数组添加方法
    {
        this._observers_.push(observer);
    }
    ObserverCollection.prototype.count = function()   //定义观察者集合个数
    {
        return this._observers_.length;
    }
    ObserverCollection.prototype.getAt = function(index)   //根据索引得到具体的莫个观察者
    {
        if (index > -1 && index < this._observers_.length)
        {
            return this._observers_[index];
        }
        return undefined;
    }

    /*---------------------------
        defined Subject
    ----------------------------*/
    function Subject(name)
    {
        this.name = name;
        this._obs_ = new ObserverCollection();
    }

    Subject.prototype.add = function(ob)  //添加观察者对象
    {
        if (ob.update)
        {
            this._obs_.add(ob);
        }
    }
    Subject.prototype.nameChanged = function()
    {
        var ob;
        for(var i=0; i < this._obs_.count(); i++)
        {
            ob = this._obs_.getAt(i);
            ob.update(this.name);   
        }
    };
    Subject.prototype.setName = function(newName)
    {
        if (this.name != newName)
        {
            this.name = newName;
            this.nameChanged();
        }
    }

    var sub = new Subject("jjy");
    sub.add(new Observer());

    sub.add(new ConcreteObserver());

    sub.setName("Jack");
    sub.setName("HongYing");
    //-->
    </script>

  • 相关阅读:
    vue + ElementUI 的横向表格代码
    localStorage.getItem
    字符串分割与数组的分割 split()VSsplice()&slice()
    ES6 Class 的基本语法
    e6 6 Symbol
    ES6 Iterator 和 for...of 循环
    ES6 数组的扩展
    element-ui上传一张图片后隐藏上传按钮
    图片上传预览原理及实现
    Winform的一些控件说明
  • 原文地址:https://www.cnblogs.com/winner/p/1423870.html
Copyright © 2011-2022 走看看