Created
October 13, 2014 20:56
-
-
Save matthewharwood/a769a6d17856de77bdee to your computer and use it in GitHub Desktop.
Cache + pubsub pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('yoangApp') | |
.service('PubSubService', function () { | |
return {Initialize:Initialize}; | |
function Initialize (scope, Cache) { | |
//Keep a dictionary to store the events and its subscriptions | |
var publishEventMap = {}; | |
scope.Cache = Cache; | |
//Register publish events | |
scope.publish = scope.publish || function () { | |
var _thisScope = this, | |
handlers, | |
args, | |
evnt; | |
//Get event and rest of the data | |
args = [].slice.call(arguments); | |
evnt = args.splice(0, 1); | |
scope.Cache.put(evnt, args); | |
scope.Cache.addToHistory(evnt, args); | |
//Loop though each handlerMap and invoke the handler | |
angular.forEach((publishEventMap[evnt] || []), function (handlerMap) { | |
handlerMap.handler.apply(_thisScope, args); | |
}); | |
}; | |
//Register Subscribe events | |
scope.subscribe = scope.subscribe || function (evnt, handler) { | |
var _thisScope = this, | |
handlers = (publishEventMap[evnt] = publishEventMap[evnt] || []); | |
//Just keep the scopeid for reference later for cleanup | |
handlers.push({ $id: _thisScope.$id, handler: handler }); | |
//When scope is destroyed remove the handlers that it has subscribed. | |
_thisScope.$on('$destroy', function () { | |
for(var i=0,l=handlers.length; i<l; i++){ | |
if (handlers[i].$id === _thisScope.$id) { | |
handlers.splice(i, 1); | |
break; | |
} | |
} | |
}); | |
}; | |
} | |
}).run(function ($rootScope, PubSubService, Cache) { | |
PubSubService.Initialize($rootScope, Cache); | |
}); | |
angular.module('yoangApp') | |
.factory('Cache', ['$cacheFactory', function($cacheFactory){ | |
var Cache = $cacheFactory('Cache'); | |
var history = {}; | |
Cache.addToHistory = function(nameSpace, val){ | |
history[nameSpace] = history[nameSpace] || []; | |
history[nameSpace].push(val); | |
}; | |
Cache.history = function(nameSpace){ | |
return !nameSpace ? history:history[nameSpace]; | |
}; | |
return Cache; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment