简体   繁体   English

angular js如何观察对象的突变?

[英]How angular js watches mutations in object?

I am curious to know how angular js watches mutations which happens to a property added to $scope . 我很好奇我想知道angular js如何监视添加到$scope的属性发生的突变。 From HTML point of view, I am able to get it, that we have some events which are fired whenever there's a change. 从HTML的角度来看,我能够得到它,我们有一些事件在发生更改时会触发。 But when it's regarding an object I am not able to understand how it actually works. 但是,当涉及到对象时,我无法理解其实际工作方式。 I can see we have a function called Object.observe . 我可以看到我们有一个名为Object.observe的函数。 But that is also deprecated as written here . 但这在这里已被弃用。 And I am pretty much sure that angular does not use Object.observe. 我非常确定angular不使用Object.observe。 The doc of angular says that one can watch mutations using $watch and $watchCollection . angular的文档说,可以使用$watch$watchCollection监视突变。 But I am not able to get how these are notified. 但是我无法获得这些通知的方式。 Can anyone help on this? 有人可以帮忙吗?

Angular will actually take a copy of the object being watched and compare against it every digest loop. Angular实际上会获取被监视对象的副本,并在每个摘要循环中与它进行比较。 So there are no notification when things change. 因此,当事情发生变化时,不会有任何通知。 It looks for changes every loop. 它寻找每个循环的变化。 And that's why watching can be expensive. 这就是为什么观看会很昂贵。 The more watches you have, the more comparisons needs to be made, and in the case where changes are found, you might end up with a new run to make sure that the change that was detected doesn't affect one of the watched objects that you already checked. 您拥有的手表越多,需要进行的比较就越多,在发现更改的情况下,您可能会进行一次新的运行,以确保检测到的更改不会影响所监视的对象之一您已经检查过了。

I would suggest the book 'Build you own AngularJS' by Tero Parviainen. 我建议Tero Parviainen写一本书“建立自己的AngularJS” Even though it's not a 100% accurate source recreation, the concepts are the same, and you'll get good insight in how angular works. 即使不是100%准确的源重新创建,概念也是相同的,并且您将对角度的工作原理有很好的了解。

Another source for understanding this part of angular is the chapter 'The Digest Loop and $apply' of the 'ng-book' . 理解角度的这一部分的另一个来源是“ ng-book” 摘要循环和$ apply”一章。 The concept is described there in a more 'accessible' form than in Teros book. 该概念以比Teros书中更“易于访问”的形式在此处进行描述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM