[英]AngularJS - $rootScope.$on - Multiple execution
在我的$onInit()
我選擇了傳播事件:
$onInit() {
this.$rootScope.$on('CANCELLED', (event) => {
this.EventService.getEventsCurrentUser('own')
.then((result) => {
this.ownEvents = result
})
})
}
我怎樣才能一次停止傳播?
您需要通過調用返回函數手動“取消注冊” $rootScope
事件。 您可以使用this.$onDestroy
在組件生命周期中做到這this.$onDestroy
。 每次執行$rootScope.$on()
時,都會一次又一次地綁定$rootScope
事件。 這就是為什么您的事件被多次調用的原因。
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
事件背后的邏輯:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.