Last active
January 3, 2021 16:37
-
-
Save turtlemonvh/10686980 to your computer and use it in GitHub Desktop.
Angular Messaging
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
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; | |
}]); |
Thanks! for many searching , this is the best solution
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;
}
}]);
thanks,very helpful
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is just what I needed. Thanks for sharing!
In case other's stumble upon this small issue, the function you register with the msgBus.onMsg() function can takes a 'scope' argument. However, you cannot access that argument within the function defined because the call to $rootScope.$emit() doesn't pass anything for a third argument (for obvious reasons). Therefore, if you want to access the scope variable, you'll have to make a separate reference to it for use within the callback function.