AngularJS $ scope。$多个事件

时间:2015-12-16 12:11:49

标签: javascript angularjs events

我有一个场景,当我需要收听通过Object传输的2个不同的事件时,我想只在两个事件都发生时才

因此,例如,如果事件触发如下:

$scope.$emit

有没有开箱即用的东西?理想情况下

$scope.$emit('first'); // do nothing $scope.$emit('second'); // execute something $scope.$emit('first'); // Do nothing $scope.$emit('first'); // Do nothing $scope.$emit('second'); // execute something

我考虑过以下几点:

$scope.$on('first', 'second', function() {});

那么有什么能让它变得更简单吗?或者有关如何改进它的一些建议?除了为此创建服务。

由于

1 个答案:

答案 0 :(得分:0)

没有内置方法可以做到这一点。我会亲自将一个新方法附加到$ rootScope:

https://jsfiddle.net/qv6m2drz/5/

var app = angular.module('jsbin', []);

app.run(['$rootScope', function($rootScope) {
  $rootScope.onAllEvents = (function() {

    var watchedEvents = {};    
    return onAllEvents;

    /*
     * Attach listeners to all events
     */
    function onAllEvents(events, fn){
        if(!events || !events.length) return ;

      events.forEach(function(evt){
        watchedEvents[evt] = false;
        this.$on(evt, function(){
            watchedEvents[evt] = true;
          tryExecute(fn);
        });
      }.bind(this));
    }

    /* 
     * Check if all `watchedEvents` have fired. If yes, run fn() and reset the events
     */
    function tryExecute(fn){
        var shouldExecute = true;
        for(evt in watchedEvents){
        if(watchedEvents.hasOwnProperty(evt) && !watchedEvents[evt]){
            shouldExecute = false;
        }
      }

      if(shouldExecute){        
        fn();
        for(evt in watchedEvents){
          if(watchedEvents.hasOwnProperty(evt)){
            watchedEvents[evt] = false;
          }
        }
      }
    }
  })();
}]);