javascript - 如何迭代对象列表,并将监视分配给它们的变量,并使用它们的回调之一?

标签 javascript angularjs watch

这是一个 jsfiddle,它完全符合我的要求:http://jsfiddle.net/4evvmqoe/1/ (除了那些最初的警报......有没有办法抑制这些警报?)。

HTML:

    <div ng-app="">
      <div ng-controller="MyCtrl">
          <div ng-repeat = "x in items">
          <input type = "checkbox" ng-model = "x.bool"/>
           {{x.label}}
          </div>
      </div>
    </div>

JS:

   function MyCtrl($scope) {
    var CheckBox = function(label, fn){
        this.label = label;
        this.fn = fn;
        this.bool = true;
    }
    $scope.items = [
        new CheckBox("aaaa", function(){alert("aaa")}),
        new CheckBox("bbbb",  function(){alert("bbb")}),
        new CheckBox("cccc",  function(){alert("ccc")})
    ];
    for (var i = 0;  i< $scope.items.length; i++){
        $scope.$watch('items['+i+']', function(newValue, oldValue){
            newValue.fn();
        }, true);
    }
}

我关心的是我做 watch 的代码:

  for (var i = 0;  i< $scope.items.length; i++){        
    $scope.$watch('items['+i+']', //<-- seriously?
       function(newValue, oldValue){ 
        newValue.fn();      
    }, true);
  }

有更好的方法吗?

问题:

  1. 如何抑制初始警报?

  2. $scope.$watch('items['+i+']', 真的是执行此操作的正确方法吗?我的意思是它有效,但是...我觉得有某种可怕的性能问题正处于危险之中。

最佳答案

修改监视以查看值是否更改,并且仅在更改时调用您的函数

$scope.$watch('items['+i+']', function(newValue, oldValue){
  if(newValue !== oldValue){
    newValue.fn();  
  }    
}, true);

watch 很昂贵,您可以摆脱 $watch 并在复选框上使用 ng-change ,这样性能会更高

例如。

http://jsfiddle.net/qbuLk2gd/

HTML:

<div ng-app="">
  <div ng-controller="MyCtrl">
      <div ng-repeat = "x in items">      
      <input type = "checkbox" ng-model = "x.bool" ng-change = "x.fn()"/>
       {{x.label}}
      </div>
  </div>
</div>

JS:

function MyCtrl($scope) {    
    var CheckBox = function(label, fn){
    this.label = label;
    this.fn = fn;
    this.bool = true;
  }

  $scope.items = [
    new CheckBox("aaaa", function(){alert("aaa")}), 
    new CheckBox("bbbb",  function(){alert("bbb")}), 
    new CheckBox("cccc",  function(){alert("ccc")})
  ];      
}

简单多了!

DEMO

关于javascript - 如何迭代对象列表,并将监视分配给它们的变量,并使用它们的回调之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34739168/

相关文章:

python - 观察属性的变化

javascript - Angular Watch 不适用于controllerAs 语法

angularjs - 在我的元素标签上添加和删除附加类

javascript - 在 AngularJS : make a directive that is a drop zone, 中拖放,在拖动时显示叠加层

javascript - 如何让Gulp读取项目根目录下Babel7的babel.config.js?

javascript - 类型错误 : undefined is not an object using d3. map

javascript - 有人可以解释以下 Angular 测试代码中调用的 evaluate() 和 dragAndDrop() 是什么吗?

javascript - Vue 3 如何在 react 对象上使用 watch 或 watchEffect(和 console.log)?

javascript - mongodb 用户配置文件添加输入时遇到问题

javascript - jQuery - 库还是框架?