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
$watchGroup vs $watchCollection?
提问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
$watchCollection
will shallow watch the properties on a single objectand notify you if one of them changes.
$watchCollection
将浅层观察单个对象的属性,并在其中一个对象发生变化时通知您。
$watchGroup
however watches a group of individual watch expressions.
$watchGroup
但是手表是一组单独的手表表情。
They are not functionally equivalent. $watchGroup
could 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 bar
property and baz
's qux
property, but they will all delegate to the same handler.
它们在功能上并不等效。$watchGroup
当您想观看应全部响应同一个回调的大量表达式时,可以使用它 - 这些可以是针对不同对象的单独表达式。这可用于观看'foo'
,'foo.bar'
和'baz.qux'
。这是 3 个不同的目标 - foo
,foo
的bar
属性和baz
的qux
属性,但它们都将委托给同一个处理程序。
By contrast, $watchCollection
will 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 foo
and baz
, but you would be notified of any changes in foo
and baz
(as opposed to just being notified for the changes on foo
itself, foo.bar
and baz.qux
.
相比之下,$watchCollection
只会浅薄地观看单个物体。这对于可能会大量更改其属性的对象(例如 - 我们自己的$scope
)来说更好。与我们的垃圾名称示例保持一致,要实现与上述相同的效果,您只需要查看foo
and baz
,但是您会收到有关foo
and 中的任何更改的通知baz
(而不是仅收到通知foo
本身foo.bar
和baz.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';