Using angular isolated scopes as event emitters
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
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