Skip to content

Instantly share code, notes, and snippets.

@Narayon
Created February 24, 2017 19:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Narayon/649767ac8dab41f7cb4f2b64ed6abc62 to your computer and use it in GitHub Desktop.
Save Narayon/649767ac8dab41f7cb4f2b64ed6abc62 to your computer and use it in GitHub Desktop.
Angular v1 Pub-Sub
// an example channel service that lets consumers
// subscribe and publish for nuclear reactor meltdowns
var CoreReactorChannel = function($rootScope) {
// local constants for the message ids.
// these are private implementation detail
var ELEVATED_CORE_TEMPERATURE_MESSAGE = "elevatedCoreMessage";
// publish elevatedCoreTemperature
// note that the parameters are particular to the problem domain
var elevatedCoreTemperature = function(core_id, temperature) {
$rootScope.$broadcast(ELEVATED_CORE_TEMPERATURE_MESSAGE,
{
core_id: core_id,
temperature: temperature
});
};
// subscribe to elevatedCoreTemperature event.
// note that you should require $scope first
// so that when the subscriber is destroyed you
// don't create a closure over it, and te scope can clean up.
var onElevatedCoreTemperature = function($scope, handler) {
$scope.$on(ELEVATED_CORE_TEMPERATURE_MESSAGE, function(event, message){
// note that the handler is passed the problem domain parameters
handler(message.core_id, message.temperature);
});
};
// other CoreReactorChannel events would go here.
return {
elevatedCoreTemperature: elevatedCoreTemperature,
onElevatedCoreTemperature: onElevatedCoreTemperature
};
};
//Usage elsewhere in the application
var MyController = function($scope, CoreReactorChannel){
// Handle core temperature changes
var onCoreTemperatureChange = function(core_id, temperature){
console.log(core_id, temperature);
}
// Let the CoreReactorChannel know the temperature has changed
$scope.changeTemperature = function(core_id, temperature){
CoreReactorChannel.elevatedCoreTemperature(core_id, temperature);
}
// Listen for temperature changes and call a handler
// Note: The handler can be an inline function
CoreReactorChannel.onElevatedCoreTemperature($scope, onCoreTemperatureChange);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment