Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using angular isolated scopes as event emitters
someModule.service('something', function($rootScope) {
var emitter = $rootScope.$new(true);
var data = whateverStuffHere;
return {
onDataUpdated: function(callback) {
//by returning the result from $on, we get
//the ability to remove event listeners easily
return emitter.$on('update', callback);
},
getData: function() {
//angular.copy is used so the data remains immutable
//and other code can't accidentally interfere/mess up the data
return angular.copy(data);
},
doSomethingThatUpdatesData: function() {
//fetch data or somethingn,
//you can trigger the listeners with..
emitter.$emit('update');
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment