你需要在 $scope $destroy 事件中解除 $scope.$on 的绑定吗? [英] Do you need to unbind $scope.$on in $scope $destroy event?
问题描述
我有使用 $on 绑定事件的指令,我需要在作用域被销毁时删除该绑定,还是自动完成?我还需要调用 $element.off 吗?
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()
listeners 丢失时会自动销毁/清理由于 E2E 绑定在您的视图中表示.请注意,对于 $rootScope.$on()
绑定不会发生这种情况.您还可以查看 $scope AngularJS 文档.
$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();
会自动销毁.- 您需要手动销毁
$rootScope.$on()
.
$scope.$on();
will be destroyed automatically.- You need to destroy
$rootScope.$on()
manually.
作用域销毁 - 当不再需要子作用域时,它是子作用域创建者有责任通过以下方式销毁它们scope.$destroy() API.这样做是为了停止传播$digest 调用子作用域并允许垃圾收集器要回收的子作用域模型.
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);
<小时>
此plnkr 将向您展示$scope.$ 的不同行为on()
和 $rootScope.$on()
.
通过在此 plunkr 中切换视图,控制器将重新绑定到您的视图.$rootScope.$on();
事件会在每次切换视图时绑定,之前不会破坏视图的事件绑定.这样 $rootScope.$on()
侦听器将被堆叠/相乘.这不会发生在 $scope.$on()
绑定上,因为它会因切换视图而被破坏(丢失 DOM 中的 E2E 绑定表示).
This plnkr will show you the different behaviors of $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');
将监听$scope.$broadcast('event')
&$rootScope.$broadcast('event')
$scope.$on('event');
will listen to$scope.$broadcast('event')
&$rootScope.$broadcast('event')
$rootScope.$on('event');
只会监听 $rootScope.$broadcast('event')
这篇关于你需要在 $scope $destroy 事件中解除 $scope.$on 的绑定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!