簡體   English   中英

AngularJS - $rootScope.$on - 多重執行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM