Javascript 取消AngularJS中的事件注册
具有控制器MyCtrl:Javascript 取消AngularJS中的事件注册,javascript,angularjs,angularjs-scope,rootscope,Javascript,Angularjs,Angularjs Scope,Rootscope,具有控制器MyCtrl: class MyCtrl { constructor($scope, $rootScope, ...) { this.$scope = $scope; this.$rootScope = $rootScope; this.doThis = _debounce(this.resize.bind(this), 300); ... } $onInit() { ... } $onDe
class MyCtrl {
constructor($scope, $rootScope, ...) {
this.$scope = $scope;
this.$rootScope = $rootScope;
this.doThis = _debounce(this.resize.bind(this), 300);
...
}
$onInit() { ... }
$onDestroy() { ... }
}
$onInit内部称为$rootScope。$on。与此类似,是另一个控制器,用于执行相同的操作,但用于不同类型的页面,比如MyCtrl2。当我从第一个转到第二个时,第一个不断被呼叫,因为它没有被破坏。我使用添加注销器描述的方法解决了这个问题。
$onInit现在:
现在,如果我从第一个控制器的页面转到第二个控制器的页面,一切正常。但是,当我单击返回第一个页面时,控制台中出现一个错误,显示:
有什么想法吗?$rootScope.“$destroy”上的$永远不会被调用,因为$rootScope永远不会被销毁
$onInit() {
this.deregisterToggleNav = this.$rootScope.$on('toggleNav', () => {
this.doThis();
});
this.deregisterDoThis = this.$rootScope.$on('listen', ̶f̶u̶n̶c̶t̶i̶o̶n̶(̶)̶ () => {
̶t̶h̶i̶s̶.̶$̶s̶c̶o̶p̶e̶.̶d̶o̶T̶h̶i̶s̶(̶)̶;̶
this.doThis();
});
̶t̶h̶i̶s̶.̶$̶r̶o̶o̶t̶S̶c̶o̶p̶e̶.̶$̶o̶n̶(̶'̶$̶d̶e̶s̶t̶r̶o̶y̶'̶,̶ ̶t̶h̶i̶s̶.̶d̶e̶r̶e̶g̶i̶s̶t̶e̶r̶D̶o̶T̶h̶i̶s̶)̶;̶
}
而是使用$onDestroy生命周期挂钩:
$onDestroy() {
this.deregisterToggleNav();
this.deregisterDoThis();
}
有关详细信息,请参阅
您可以使用$scope.$on的返回值来注销事件。REFERE-抱歉,我不明白。您可以尝试使用$STATECHANGESSUCCESS事件重新绑定$scope。$on handlertry:this.deregisterDoThis=this。$rootScope.$on'listen',=>{this.$scope.doThis;}@除了使用ES6语法之外,还有什么其他区别吗?它具有相同的行为。不应该在$onDestroy中进行更改吗?比如将deregisterDoThis设置为null或false之类的
$onInit() {
this.deregisterToggleNav = this.$rootScope.$on('toggleNav', () => {
this.doThis();
});
this.deregisterDoThis = this.$rootScope.$on('listen', ̶f̶u̶n̶c̶t̶i̶o̶n̶(̶)̶ () => {
̶t̶h̶i̶s̶.̶$̶s̶c̶o̶p̶e̶.̶d̶o̶T̶h̶i̶s̶(̶)̶;̶
this.doThis();
});
̶t̶h̶i̶s̶.̶$̶r̶o̶o̶t̶S̶c̶o̶p̶e̶.̶$̶o̶n̶(̶'̶$̶d̶e̶s̶t̶r̶o̶y̶'̶,̶ ̶t̶h̶i̶s̶.̶d̶e̶r̶e̶g̶i̶s̶t̶e̶r̶D̶o̶T̶h̶i̶s̶)̶;̶
}
$onDestroy() {
this.deregisterToggleNav();
this.deregisterDoThis();
}