AngularJS 模拟 pub/sub、data storage

1. data storage:

MyApp.factory('dataStorage', [
function() {
    var stroage = {};
    var exports;
    
    exports = {
        get: function() {
            return storage[key];
        },
        set: function() {
            storage[key] = value;
        }
    };
    return exports;
}]);



2. pb

MyApp.factory('channel', [function() {
    var exports;
    var channels = {};
    exports = {
        subscribe: function(topic, callback) {
            if (!_.isArray(channels[topic])) {
                channels[topic] = [];
            }
            var handlers = channels[topic];
            handlers.push(callback);
        },
        unsubscribe: function(topic, callback) {
            if (_.isArray(channels[topic])) {
                var handlers = channels[topic];
                var index = _.indexOf(handlers, callback);
                if (index >= 0) {
                    handlers.splice(index, 1);
                }
            }
        },
        publish: function(topic, data) {
            var self = this;
            var handlers = channels[topic] || [];
            _.each(handlers, function(handler) {
                handler.apply(self, [data]);
            });
        }
    };
    return exports;
}]);

你可能感兴趣的:(AngularJS 模拟 pub/sub、data storage)