Last active
December 4, 2016 14:04
-
-
Save jhartikainen/7f3edf816e67e86a9986b6e4341a88e1 to your computer and use it in GitHub Desktop.
Using angular isolated scopes as event emitters
This file contains hidden or 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
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