AngularJS : 为什么在`$watch`监听器中检查newValue和oldValue是否相同?
AngularJS : Why to check whether newValue is the same as oldValue in `$watch` listener?
我多次看到下面的模式:
$scope.$watch('full_name', function(newVal, oldVal, scope) {
if(newVal === oldVal) {
return
} else {
}
}
我不太明白if(newVal==oldVal)
分支,因为它看起来没用..监听回调函数不应该只在观察值改变时调用吗?如果是这样,newVal
不应该总是与 oldVal
不同吗?
如果没有,有没有人举例说明在 newVal==oldVal
分支中可以做什么?
if (newVal === oldVal)
构造是为了跳过初始化。 AngularJS documentation 声明当你附加手表时,它会用 undefined, undefined
调用一次回调。为防止您的监视函数将此调用误认为是模型更改,您可以添加 if
结构。
After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.
我多次看到下面的模式:
$scope.$watch('full_name', function(newVal, oldVal, scope) {
if(newVal === oldVal) {
return
} else {
}
}
我不太明白if(newVal==oldVal)
分支,因为它看起来没用..监听回调函数不应该只在观察值改变时调用吗?如果是这样,newVal
不应该总是与 oldVal
不同吗?
如果没有,有没有人举例说明在 newVal==oldVal
分支中可以做什么?
if (newVal === oldVal)
构造是为了跳过初始化。 AngularJS documentation 声明当你附加手表时,它会用 undefined, undefined
调用一次回调。为防止您的监视函数将此调用误认为是模型更改,您可以添加 if
结构。
After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.