Skip to content

Instantly share code, notes, and snippets.

@turtlemonvh
Last active January 3, 2021 16:37
Show Gist options
  • Save turtlemonvh/10686980 to your computer and use it in GitHub Desktop.
Save turtlemonvh/10686980 to your computer and use it in GitHub Desktop.
Angular Messaging
var MyApp = angular.module('MyApp');
MyApp.factory('msgBus', ['$rootScope', function($rootScope) {
var msgBus = {};
msgBus.emitMsg = function(msg, data) {
data = data || {};
$rootScope.$emit(msg, data);
};
msgBus.onMsg = function(msg, func, scope) {
var unbind = $rootScope.$on(msg, func);
if (scope) {
scope.$on('$destroy', unbind);
}
return unbind;
};
return msgBus;
}]);
@ralphv
Copy link

ralphv commented Jul 3, 2014

This is how we approached this, basically we replaced the $rootScope.$on function with another that maintains the same functionality, but if it takes a third parameters (scope), it will attach a destroy event to it that automatically removed the rootScope event.

app.run(["$rootScope", function($rootScope) {
var _nop = function() {};
var _ref = $rootScope.$on;
$rootScope.$on = function(name, listener, scope) {
var unbind = _ref.call($rootScope, name, listener);
if(scope && unbind) {
scope.$on('$destroy', unbind);
return _nop;
}
return unbind;
}
}]);

@liekkas
Copy link

liekkas commented Jul 9, 2015

thanks,very helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment