繁体   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