简体   繁体   English

如何在angularjs的for循环中动态创建$ rootScope。$ on事件侦听器

[英]How to dynamically create $rootScope.$on event listeners in a for loop in angularjs

I want to dynamically create event listeners in an angularjs service, however it seems that each $rootScope.$on event listener I create in the for loop in the service is overwritten by the following event listener. 我想在angularjs服务中动态创建事件监听器,但是似乎我在服务的for循环中创建的每个$rootScope.$on事件监听器都被以下事件监听器覆盖。 How can I dynamically create $rootScope.$on even listeners without overwriting the previous event listener? 如何$rootScope.$on不覆盖以前的事件侦听器的情况下$rootScope.$on侦听器$rootScope.$on动态创建$rootScope.$on I create events using broadcasts from my controller like $rootScope.$broadcast(EVENTS.userDeleteSuccess.event); 我使用控制器中的广播创建事件,例如$rootScope.$broadcast(EVENTS.userDeleteSuccess.event); .

My EVENTS constant looks like: 我的EVENTS常量如下所示:

myApp.constant('EVENTS', {
    userDeleteSuccess: {
        event: 'user-delete-success',
        type: 'success',
        message: 'User successfully deleted'
    },
    ...,
    siteDeleteSuccess: {
        event: 'site-delete-success',
        type: 'success',
        message: 'Site successfully deleted'
    }
}

My service looks like: 我的服务如下:

myApp.service("Alert", function($rootScope, EVENTS) {

    var show = function(type, message) {

        $rootScope.alert = {
            type: type,
            message: message,
            show: true
        };
    };

    // Initialized on application startup, this is the problem method!

    this.initialize = function() {
        for(var event in EVENTS) {
          if(!EVENTS.hasOwnProperty(event)) break;
          var _event = EVENTS[event];
          $rootScope.$on(_event.event, function() {
            show(_event.type, _event.message);
          });
        }
      };

      return this;
});

The only event that ever gets broadcasted is always the last event in the object ( siteDeleteSuccess in this case). 广播的唯一事件始终是对象中的最后一个事件(在这种情况下为siteDeleteSuccess )。 How can I dynamically create an event listener in a for loop that doesn't overwrite the previous $rootScope.$on event listener? 如何在不覆盖以前的$rootScope.$on事件侦听器的for循环中动态创建事件侦听器?

You can do two things use an IIFE or just bind the argument(s) so they get passed into the function 您可以使用IIFE做两件事,也可以只绑定参数,以便将它们传递给函数

IIFE 国际教育展

(function(event){
    $rootScope.$on(event.event, function() {
        show(event.type, event.message);
    });
})(_event);

Binding: 捆绑:

$rootScope.$on(_event, function(event) {
    show(event.type, event.message);
}.bind(null,_event));

bind docs 绑定文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM