Skip to content

Instantly share code, notes, and snippets.

@campbellwmorgan
Created December 15, 2015 14:26
Show Gist options
  • Save campbellwmorgan/9ffe5243b8049678982e to your computer and use it in GitHub Desktop.
Save campbellwmorgan/9ffe5243b8049678982e to your computer and use it in GitHub Desktop.
/**
* Module for abstracting pub sub
* across all scopes
* @example
*
* var events = PubSub($scope, 'MyModule:');
* events.on('AnotherModule:Update', function(e, data) {
* console.log(data, 'from Update');
* });
* events.emit("Change", {myData:'data'});
* // emits event "MyModule:Change"
*
*/
angular.module('testApp')
.factory('PubSub', function PubSub($rootScope){
return function($scope, customPrefix) {
var prefix = customPrefix || '';
return {
on: function (event, callback) {
var unsubscribe = $rootScope.$on(customPrefix + event, callback);
$scope.$on('$destroy', unsubscribe);
return unsubscribe;
},
emit: function (event, data) {
return $rootScope.$emit(customPrefix + event, data);
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment