Skip to content

Instantly share code, notes, and snippets.

@jhartikainen
Last active December 4, 2016 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jhartikainen/7f3edf816e67e86a9986b6e4341a88e1 to your computer and use it in GitHub Desktop.
Save jhartikainen/7f3edf816e67e86a9986b6e4341a88e1 to your computer and use it in GitHub Desktop.
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