Advertisement
Guest User

Untitled

a guest
Feb 24th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. // an example channel service that lets consumers
  2. // subscribe and publish for nuclear reactor meltdowns
  3.  
  4. var CoreReactorChannel = function($rootScope) {
  5.  
  6. // local constants for the message ids.
  7. // these are private implementation detail
  8. var ELEVATED_CORE_TEMPERATURE_MESSAGE = "elevatedCoreMessage";
  9.  
  10. // publish elevatedCoreTemperature
  11. // note that the parameters are particular to the problem domain
  12. var elevatedCoreTemperature = function(core_id, temperature) {
  13. $rootScope.$broadcast(ELEVATED_CORE_TEMPERATURE_MESSAGE,
  14. {
  15. core_id: core_id,
  16. temperature: temperature
  17. });
  18. };
  19.  
  20. // subscribe to elevatedCoreTemperature event.
  21. // note that you should require $scope first
  22. // so that when the subscriber is destroyed you
  23. // don't create a closure over it, and te scope can clean up.
  24. var onElevatedCoreTemperature = function($scope, handler) {
  25. $scope.$on(ELEVATED_CORE_TEMPERATURE_MESSAGE, function(event, message){
  26. // note that the handler is passed the problem domain parameters
  27. handler(message.core_id, message.temperature);
  28. });
  29. };
  30.  
  31. // other CoreReactorChannel events would go here.
  32.  
  33. return {
  34. elevatedCoreTemperature: elevatedCoreTemperature,
  35. onElevatedCoreTemperature: onElevatedCoreTemperature
  36. };
  37. };
  38.  
  39.  
  40. //Usage elsewhere in the application
  41. var MyController = function($scope, CoreReactorChannel){
  42. // Handle core temperature changes
  43. var onCoreTemperatureChange = function(core_id, temperature){
  44. console.log(core_id, temperature);
  45. }
  46.  
  47. // Let the CoreReactorChannel know the temperature has changed
  48. $scope.changeTemperature = function(core_id, temperature){
  49. CoreReactorChannel.elevatedCoreTemperature(core_id, temperature);
  50. }
  51.  
  52. // Listen for temperature changes and call a handler
  53. // Note: The handler can be an inline function
  54. CoreReactorChannel.onElevatedCoreTemperature($scope, onCoreTemperatureChange);
  55. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement