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

时间:2014-07-12 07:09:18

标签: angularjs

我正在阅读有关范围方法$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 个答案:

答案 0 :(得分:1)

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

正如你所说,$watch(watchExpression, [listener])

有2个参数
  • watchExpression
    每次调用$ digest()时都会调用watchExpression,并且应该返回将要监视的值 监视表达式可以是stringfunction。 如果你指定一个函数,这是一个的监听器,而是一个多次调用的比较函数,所以不要在这里做任何花哨的东西;)
    该比较功能用于角度脏检查 关于这方面的更多细节可以在angularJs的创建者的视频的这一部分中找到:https://www.youtube.com/watch?feature=player_detailpage&v=ZhfUv0spHCY#t=1988

  • listener
    只要watchExpression的值发生变化,就会调用此函数 因此,这是更新模型和实现业务逻辑的理想场所