zoukankan      html  css  js  c++  java
  • 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");

  • 相关阅读:
    利用Delegator模式保护javascript程序的核心与提高执行性能 (转)
    工作流
    蓝色垂直滑动效果的CSS导航
    JavaScript 多级联动浮动菜单 (第二版) (转)
    虚线效果水平CSS菜单
    红色玻璃效果水平CSS菜单
    CSS绿色水平多级下拉菜单
    ASP.NET中的Path(转)
    黑色与红色形成的水平CSS导航菜单
    紫罗兰水平CSS菜单
  • 原文地址:https://www.cnblogs.com/jjyjjyjjy/p/1420985.html
Copyright © 2011-2022 走看看