Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngReact: watch-depth attribute types explained

Recently I found an awesome library that allows for React components to be used in Angular applications, called ngReact

My question is about the watch-depth attribute that can be declared on a reactDirective component:

<body ng-app="app">
  <div ng-controller="helloController">
    <hello-component watch-depth="reference" fname="person.fname" lname="person.lname"></hello-component>
  </div>
</body>

Looking at ngReact documentation for the reactDirective service I see that there are 3 possible values for watch-depth:

  • Reference
  • Collection
  • Value

In my initial exploration using ngReact I have been sticking with using the default value option.

My question is, what are the differences between these types?

Simple examples for when each watch-depth type is ideal to use would be great!

like image 927
Cumulo Nimbus Avatar asked Nov 20 '15 18:11

Cumulo Nimbus


1 Answers

The answer has to do with how angular's $watch works. There are 3 ways angular applies $watch: Reference, Collection, Value (as you've already mentioned).

Reference:

Reference looks at the reference of a value and will only register a change (and cause a rerender) if that reference changes. This is the least expensive watch type. example of a reference change:

$scope.userArray = newUserArray

Collection:

A watch-depth of Collection is more in depth. It will look inside the collection. It will register a change if a Watch By Reference would have fired, or if a new item is added, removed, or reordered within the collection.

$scope.userArray.push(newUser);

Value:

A watch-depth of value is the most expensive. It will watch the values within a collection. It will register a change if Watch By Reference would have fired, if Watch By Collection would have fired, or if a value within the collection changes.

$scope.userArray[0].age = 32;

This answer was heavily inspired by an excellent article written by Tero Parviainen, https://teropa.info/blog/2014/01/26/the-three-watch-depths-of-angularjs.html

like image 81
Tenbrink Avatar answered Sep 20 '22 10:09

Tenbrink