JS观察者模式简介及实例

一、概念
观察者(observer)模式:又称订阅/发布(subscriber/publisher)模式,
被观察者(也成发布者或者主题)
观察者(也称订阅者)
当发生特定事件时,发布者通知(调用)所有订阅者,以事件对象的形式传递消息。
通过这种方式,促成松耦合。
二、属性及方法
subscribers : 记录订阅者的数组;
subscribe() : 将订阅者添加到subscribers数组的方法;
unsubscribe() : 从订阅者数组subscribers删除订阅者的方法;
publish() : 循环遍历subscribers数组,调用每个订阅者注册时提供的方法。
三、实现

// 发布功能实现实例
    var publisher = {
        subscribers: {
            any: []
        },
        subscribe: function(fn, type) {
            type = type || 'any';
            if (typeof this.subscribers[type] === 'undefined') {
                this.subscribers[type] = [];
            }
            this.subscribers[type].push(fn);
        },
        unsubscribe: function(fn, type) {
            this.visitSubscribers('unsubscribe', fn, type);
        },
        publish: function(publication, type) {
            this.visitSubscribers('publish', publication, type);
        },
        visitSubscribers: function(action, arg, type) {
            var pubtype = type || 'any',
                subscribers = this.subscribers[pubtype],
                i,
                max = subscribers.length;
            for (i = 0; i < max; i++) {
                if (action === 'publish') {
                    subscribers[i](arg);
                } else {
                    if (subscribers[i] === arg) {
                        subscribers.splice(i, 1);
                    }
                }
            }
        }
    }
    // 将发布方法复制到传入的对象中
    function makePublisher(o) {
        for(var i in publisher) {
            if (publisher.hasOwnProperty(i) && typeof publisher[i] === 'function') {
                o[i] = publisher[i];
            }
        }
        o.subscribers = {
            any: []
        }
    }
    // 测试
    var publish = {
        priceIncrease: function(flux) {
        this.publish('Price Increase :' + flux);
        },
        priceDecrease: function(flux) {
            this.publish('Price Decrease :' + flux);
        },
    }
    makePublisher(publish);

    var price = 100;
    var board = {
        // _price: 100,
        changePrice: function(content) {
            var flux = Number(content.split(":")[1]);
            price =  price + flux
            document.getElementById("priceSpan").innerHTML = price;
        },
        // getPrice: function() {
        //  return this._price;
        // }
    }
    publish.subscribe(board.changePrice);

你可能感兴趣的:(JS观察者模式简介及实例)