3)Javascript设计模式:Observer模式

Observer模式

var Observer = (function() {

    var instance = null;

    function Observe() {
        this.events = {}
    }

    Observe.prototype.subscribe = function(eventName, callback) {
        var actions = this.events[eventName];
        if( !actions) {
            actions = this.events[eventName] = [];
        }
        actions.push(callback);

    };

    Observe.prototype.publish = function(eventName) {
        var args = Array.prototype.slice.call(arguments).slice(1);
        var actions = this.events[eventName];
        if(actions) {
            for(var cb in actions) {
                actions[cb].apply(null, args)
            }
        }
        else {
            console.log(eventName || '' + ' is not registered');
        }
    };

    function returnFunction() {
        if(!instance) {
            instance = new Observe();
        }
        return instance;
    }

    returnFunction.toString = function() {
        console.log('Use Observer() to get instance');
    };

    return returnFunction;

})();

你可能感兴趣的:(3)Javascript设计模式:Observer模式)