条件EventListener

时间:2015-11-18 06:37:47

标签: javascript angularjs javascript-events event-handling

我只是想知道是否有一种方法来定义条件事件监听器,即只有在满足某些条件时才能监听事件。

我想我要求一个非正统的东西,或者已经存在一种我不知道的方式。

示例:

当ng-repeat结束时,让'lastRepeat'成为指令发出的事件。

app.controller('ctrl',function($scope){
  $scope.$on('lastRepeat', callback);  // Here the callback will be called every time lastRepeat event is emitted by the directive 
});

但我正在寻找的是这样的(这是我想到的,解决方案不需要使用相同的方法):

app.controller('ctrl',function($scope){
  function foo(){
    if(bool)
      $scope.$on('lastRepeat', callback); // Problem listening like this is that a listener is created everytime foo is called and condition is met and hence we end up having multiple listeners
  }
)};

基本上我想避免多次创建监听器。有没有办法可以将这个监听器存储为变量,只有在满足某些条件时才能监听。

1 个答案:

答案 0 :(得分:2)

怎么样:

app.controller('ctrl', function($scope) {

  var condition = false;
  var callback = function () {};

  $scope.$on('lastRepeat', function() {
    if (!condition) return;
    callback();    
  });
});