gpt4 book ai didi

javascript - 深 $watch 与 $watchCollection : $var behavior

转载 作者:行者123 更新时间:2023-11-28 00:45:39 26 4
gpt4 key购买 nike

$watchCollection 是否能够忽略对以 $ 开头的属性的更改?使用深度 $watch 时已经存在此行为,因为它依赖于 angular.equals 进行比较。

理想情况下,$watchCollection 是浅层监视对象的首选(也是唯一)方法。不同的行为有合理的理由吗?

示例

$scope.foo = {
$bar: 'someValue',
baz: 123456
};

$scope.$watch('foo', function() {
console.log('watch');
}, true);

$scope.$watchCollection('foo', function(){
console.log('watchCollection');
});

// logs 'watch'
// logs 'watchCollection'
$scope.foo.baz = 654321;

// logs 'watchCollection'
$scope.foo.$bar = 'changed'

最佳答案

取自 Angular $watch 源代码注释:

When objectEquality == true, inequality of the watchExpression is determined according to the {@link angular.equals} function.

我们可以从angular.equals文档中看到:

During a property comparison, properties of function type and properties with names that begin with $ are ignored.

这解释了为什么 $ 属性在 $watch 比较中被忽略。

$watchCollection 函数实际上会进行自己的比较,以检查对象是否相同,它们是否是数组,如果是数组,它会检查值是否相同是相同的。直接取自源代码:

if (oldLength !== newLength) {
// if lengths do not match we need to trigger change notification
changeDetected++;
oldValue.length = oldLength = newLength;
}
// copy the items to oldValue and look for changes.
for (var i = 0; i < newLength; i++) {
oldItem = oldValue[i];
newItem = newValue[i];

bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
if (!bothNaN && (oldItem !== newItem)) {
changeDetected++;
oldValue[i] = newItem;
}
}

我无法判断他们是否是故意这样做的,但这确实是这样的=D

关于javascript - 深 $watch 与 $watchCollection : $var behavior,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27432193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com