JavaScript观察者模式

来源:互联网 发布:sql数据库教学百度云 编辑:程序博客网 时间:2024/06/16 18:19

观察者的使用场合就是:当一个对象的改变需要同时改变其它对象,并且它不知道具体有多少对象需要改变的时候,就应该考虑使用观察者模式。

总的来说,观察者模式所做的工作就是在解耦,让耦合的双方都依赖于抽象,而不是依赖于具体。从而使得各自的变化都不会影响到另一边的变化。




<!DOCTYPE HTML><html>    <head>        <meta charset="utf-8" />        <script type="text/javascript">            // 被观察者            var Subject = function() {                this.obArray = [];            };            Subject.prototype = {                addObserver : function(observer) {                    console.log('addObserver...');                    this.obArray.push(observer);                    console.log('addObserver() obArray.length:' + this.obArray.length);                }                ,removeObserver : function(observer) {                    console.log('removeObserver...');                    this.obArray = this.obArray.filter(function(element){                        return element != observer;                    });                    console.log('removeObserver() obArray.length:' + this.obArray.length);                }                ,notifyObservers : function() {                    console.log('notifyObservers...');                    this.obArray.forEach(function(element, index, array){                        element.update();                    });                }                ,doSomething : function() {                    console.log('doSomething...');                    this.notifyObservers();                }            };            // 观察者            var Observer = function() {};            Observer.prototype = {                update : function() {                    console.log('update...');                }            };            var testSubject = new Subject();            var testObserver = new Observer();            testSubject.addObserver(testObserver);            testSubject.doSomething();            testSubject.removeObserver(testObserver);        </script>    </head>    <body>    </body></html>


0 0
原创粉丝点击