javascript 观察者模式

 <script>

        function Subject(){
            var _this = this
            this.observers = []
            this.attach = function (observer) {
                _this.observers.push(observer)
            }

            this.detach = function(observer){
                var index = _this.observers.indexOf(observer)
                _this.observers.splice(index,1)
            }

            this.notifyObservers = function(newState){
                for(var i=0;i < _this.observers.length;i++)
                {
                    (_this.observers[i]).update(newState)
                }
            }
        }


        function Observer(){
            var observerState;
            this.update =function(state){
                observerState = state
                console.log(state)
            }
        }

        var subject = new Subject()
        subject.attach(new Observer())

        subject.notifyObservers('hello')


    </script>

上面是仿照java 的观察者模式写的

下面把它修改成发布订阅模式风格:

参考:https://github.com/reactjs/redux/blob/master/src/createStore.js

<script>

        function Subject(){
            var _this = this
            this.listeners = []
            this.subscribe = function (listener) {
                _this.listeners.push(listener)
            }

            this.unsubscribe = function(listener){
                var index = _this.listeners.indexOf(listener)
                _this.listeners.splice(index,1)
            }

            this.dispatch = function(newState){
                for(var i=0;i < _this.listeners.length;i++)
                {
                    const listener =  (_this.listeners[i])
                    listener(newState)
                }
            }
        }


        function listener(data){
            console.log(data)
        }

        var subject = new Subject()
        subject.subscribe(listener)

        subject.dispatch('hello')


    </script>

 

posted @ 2017-06-07 16:03  JonasYu  阅读(136)  评论(0编辑  收藏  举报