javascript $watchGroup 与 $watchCollection?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30220895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:54:40  来源:igfitidea点击:

$watchGroup vs $watchCollection?

javascriptangularjsangularjs-scope

提问by Atav32

There're 2 ways to watch a group of variablesin Angular. But what's the difference between them?

两种方法可以在 Angular 中观察一组变量。但是它们之间有什么区别呢?

They both seem to do shallow watches. Are there situations where one is obviously preferable over the other?

他们俩似乎都做浅表。是否存在一种明显优于另一种的情况?

回答by Dan Pantry

$watchCollectionwill shallow watch the properties on a single objectand notify you if one of them changes.

$watchCollection将浅层观察单个对象的属性,并在其中一个对象发生变化时通知您。

$watchGrouphowever watches a group of individual watch expressions.

$watchGroup但是手表是一组单独的手表表情。

They are not functionally equivalent. $watchGroupcould be used when you want to watch a multitude of expressions that should all respond to the same callback - these could be individual expressions that target different objects. This could be used for watching 'foo', 'foo.bar', and 'baz.qux'. These are 3 different targets - foo, foo's barproperty and baz's quxproperty, but they will all delegate to the same handler.

它们在功能上并不等效。$watchGroup当您想观看应全部响应同一个回调的大量表达式时,可以使用它 - 这些可以是针对不同对象的单独表达式。这可用于观看'foo''foo.bar''baz.qux'。这是 3 个不同的目标 - foo,foobar属性和bazqux属性,但它们都将委托给同一个处理程序。

By contrast, $watchCollectionwill only shallow watch a single object. This makes it better for an object that might change it's properties a lot (for example - our very own $scope). In keeping with our rubbish name examples, to achieve the same as above you would only want to watch fooand baz, but you would be notified of any changes in fooand baz(as opposed to just being notified for the changes on fooitself, foo.barand baz.qux.

相比之下,$watchCollection只会浅薄地观看单个物体。这对于可能会大量更改其属性的对象(例如 - 我们自己的$scope)来说更好。与我们的垃圾名称示例保持一致,要实现与上述相同的效果,您只需要查看fooand baz,但是您会收到有关fooand 中的任何更改的通知baz(而不是仅收到通知foo本身foo.barbaz.qux.

回答by HankScorpio

Here's an example of where you'd use each one.

下面是一个示例,说明您将在何处使用它们。

$scope.data = ['Abc', 'Bcd', 'Cde', 'Def'];
$scope.$watchCollection('data', function(){...});
// responds to changes within $scope.data
// The following line will trigger the watch function:
$scope.data[0] = 'FOO';

-

——

$scope.data = ['Abc', 'Bcd', 'Cde', 'Def'];
$scope.$watchGroup('data', function(){...});
// responds to changes on the properties (or functions, etc.)
// Any angular expression can be used in $scope.data
// The following line will trigger the watch function:
$scope.Abc = 'FOO';