设计模式之观察者模式


<script>
var sel =document.getElementById('sel');
    sel.observes =[];
    sel.attach =function (obj) {
        sel.observes[sel.observes.length] = obj;
    };

    sel.detach = function (obj) {
        for( var i=0; i < sel.observes.length; i++) {
            if(this.observes[i] == obj) {
                delete this.observes[i];
            }
        }
    };

    sel.onchange = sel.notify =function () {
        for( var i=0; i < sel.observes.length; i++) {
//
              this.observes[i].update(this);
        }
    };
    var test2 = document.getElementById('test2');
    var test3 = document.getElementById('test3');
    test3.update = function (sel) {
        if(sel.value == '1'){
            this.innerHTML = '2';
        } else if(sel.value == '0') {
            this.innerHTML ='a';
        }
    };
    test2.update = function (sel) {
        if(sel.value == '1'){
            this.innerHTML = '1';
        } else if(sel.value == '0') {
            this.innerHTML ='s';
        }
    };

    sel.attach(test2);
    sel.attach(test3);
    </script>