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

时间:2015-02-24 18:05:39

标签: javascript angularjs javascript-events

我想在angularjs服务中动态创建事件侦听器,但似乎我在服务的$rootScope.$on循环中创建的每个for事件侦听器都被以下事件侦听器覆盖。如何在不覆盖先前事件侦听器的情况下动态创建$rootScope.$on偶数侦听器?我使用来自我的控制器的广播来创建事件,例如$rootScope.$broadcast(EVENTS.userDeleteSuccess.event);

我的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'
    }
}

我的服务如下:

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;
});

广播的唯一事件始终是对象中的最后一个事件(在本例中为siteDeleteSuccess)。如何在for循环中动态创建事件监听器,而不会覆盖先前的$rootScope.$on事件监听器?

1 个答案:

答案 0 :(得分:1)

您可以使用IIFE做两件事,或者只是绑定参数,以便将它们传递给函数

IIFE

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

绑定:

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

bind docs