I have directive that bind event using $on do I need to remove that binding when scope is destroyed, or is it done automatically? Also do I need to call $element.off?
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
$element.on('load', function() {
$element[0].contentWindow.focus();
});
$scope.$on('iframe:focus', function() {
$element[0].contentWindow.focus();
});
}
};
$scope.$on()
listenerers will be destroyed / cleaned up automatically when it loses its representation due to E2E binding in your view. Note that this will not happen for $rootScope.$on()
bindings. You could also take a look at the $scope documentation of AngularJS.
$scope.$on();
will be destroyed automatically.$rootScope.$on()
manually.Scope Destruction - When child scopes are no longer needed , it is the responsibility of the child scope creator to destroy them via scope.$destroy() API. This is done in order to stop propagation of $digest calls into the child scope and allow for memory used by the child scope models to be reclaimed by the garbage collector.
$rootScope.$on()
://bind event
var registerScope = $rootScope.$on('someEvent', function(event) {
console.log("fired");
});
// clean up
$scope.$on('$destroy', registerScope);
$scope.$on()
and $rootScope.$on()
.By switching the view in this plunkr the controller will be rebinded to your view. The $rootScope.$on();
event is binded every time you switch a view without destroying the event bindings of the view before. In that way the $rootScope.$on()
listeners will be stacked/multiplied. This will not happen to the $scope.$on()
bindings because it will be destroyed by switching the view (losing the E2E binding representation in DOM).
$scope.$on('event');
will listen to $scope.$broadcast('event')
& $rootScope.$broadcast('event')
$rootScope.$on('event');
will only listen to $rootScope.$broadcast('event')
No, you don't need to remove that binding. It will be removed when the scope is destroyed. However if you bind event to $rootScope always remember to unbind it! It can be done easily like this:
var unregister = $rootScope.$on('eventName', function(e) {
//doSomething
});
$scope.$on('$destroy', unregister);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With