AngularJS - $rootScope.$on - 多次执行
AngularJS - $rootScope.$on - Multiple execution
在我的 $onInit()
中,我选择了传播事件:
$onInit() {
this.$rootScope.$on('CANCELLED', (event) => {
this.EventService.getEventsCurrentUser('own')
.then((result) => {
this.ownEvents = result
})
})
}
如何一次性停止传播?
您需要通过调用 return 函数手动 "unregister" $rootScope
事件。您可以使用 this.$onDestroy
对组件生命周期进行处理。 $rootScope
事件在每次 $rootScope.$on()
执行时一次又一次地绑定。这就是为什么您的事件被多次调用的原因。
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $rootScope) {
var registerScope = null;
this.$onInit = function () {
//register rootScope event
registerScope = $rootScope.$on('CANCELLED', function(event) {
console.log("fired");
});
}
this.$onDestroy = function () {
//unregister rootScope event by calling the return function
registerScope();
}
});
另请查看此答案,这将帮助您理解 $rootScope
和 $scope
事件背后的逻辑:
- How to use component lifecycles
在我的 $onInit()
中,我选择了传播事件:
$onInit() {
this.$rootScope.$on('CANCELLED', (event) => {
this.EventService.getEventsCurrentUser('own')
.then((result) => {
this.ownEvents = result
})
})
}
如何一次性停止传播?
您需要通过调用 return 函数手动 "unregister" $rootScope
事件。您可以使用 this.$onDestroy
对组件生命周期进行处理。 $rootScope
事件在每次 $rootScope.$on()
执行时一次又一次地绑定。这就是为什么您的事件被多次调用的原因。
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $rootScope) {
var registerScope = null;
this.$onInit = function () {
//register rootScope event
registerScope = $rootScope.$on('CANCELLED', function(event) {
console.log("fired");
});
}
this.$onDestroy = function () {
//unregister rootScope event by calling the return function
registerScope();
}
});
另请查看此答案,这将帮助您理解 $rootScope
和 $scope
事件背后的逻辑:
- How to use component lifecycles