代码之家  ›  专栏  ›  技术社区  ›  Max Koretskyi

$watch API描述-第一个被描述为监听器函数的函数,为什么?

  •  1
  • Max Koretskyi  · 技术社区  · 10 年前

    我正在阅读有关scope方法的文档 $watch here 。该方法接受: $watch(watchExpression, [listener] ; 然后,他们提供了示例:

    // let's assume that scope was dependency injected as the $rootScope
    var scope = $rootScope;
    scope.name = 'misko';
    scope.counter = 0;
    
    expect(scope.counter).toEqual(0);
    scope.$watch('name', function(newValue, oldValue) {
     scope.counter = scope.counter + 1;
    });
    expect(scope.counter).toEqual(0);
    
    scope.$digest();
    // the listener is always called during the first $digest loop after it was registered
    expect(scope.counter).toEqual(1);
    
    scope.$digest();
    // but now it will not be called unless the value changes
    expect(scope.counter).toEqual(1);
    
    scope.name = 'adam';
    scope.$digest();
    expect(scope.counter).toEqual(2);
    
    
    
    // Using a listener function
    var food;
    scope.foodCounter = 0;
    expect(scope.foodCounter).toEqual(0);
    scope.$watch(
     // This is the listener function --------- WHY ?????????????
     function() { return food; },
     // This is the change handler ---- THIS SHOULD BE A LISTNER FUNCTION
     function(newValue, oldValue) {
       if ( newValue !== oldValue ) {
         // Only increment the counter if the value changed
         scope.foodCounter = scope.foodCounter + 1;
       }
     }
    );
    // No digest has been run so the counter will be zero
    expect(scope.foodCounter).toEqual(0);
    
    // Run the digest but since food has not changed count will still be zero
    scope.$digest();
    expect(scope.foodCounter).toEqual(0);
    
    // Update food and run digest.  Now the counter will increment
    food = 'cheeseburger';
    scope.$digest();
    expect(scope.foodCounter).toEqual(1);
    

    我不明白的是他们为什么提到 function() { return food; } 在第二个示例中 // This is the listener function 如果这是一个函数 should return the value that will be watched. 这是一个 watchExpression ?

    1 回复  |  直到 10 年前
        1
  •  1
  •   jantimon    10 年前

    该评论有点误导,您可能会提出问题或请求改进。

    正如你所说的,有两个论点 $watch(watchExpression, [listener])

    • watchExpression
      每次调用$digital()时都会调用watchExpression,并应返回将被监视的值。
      watch表达式可以是 string function . 如果指定函数,则为 侦听器,而是一个比较函数,它将被多次调用,所以不要在这里做任何花哨的事情;)
      此比较函数用于角度脏检查。
      angularJs的创建者在视频的这一部分中可以找到更多关于这一点的详细信息: https://www.youtube.com/watch?feature=player_detailpage&v=ZhfUv0spHCY#t=1988

    • listener
      每当 watchExpression 变化。
      因此,这是一个更新您的模型和执行您的花式业务逻辑的完美地方