-1

Let's say we have a collection:

var model = new Model([1,2,3,4,5]) and we render it with some javascript app framework like backbone, react, ember, angular, vue, etc. so the final result looks like this:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>

Now we add an item at the start:

model.unshift(0)

This would automaticallly redraw the collection somehow, so it would look like this:

<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>

Now the part I'm curious about is how do these frameworks detect that it's only the <div>0</div> that's new and prepend it to the collection view instead of thinking that it's a completely new collection (since all of the items indices have changed) and redraw the whole thing?

I am curious if there's some common logic they're using, and what is considered the "best practice" nowadays. Thank you!

Vlad
  • 8,038
  • 14
  • 60
  • 92

1 Answers1

1

I can't speak for all frameworks, but I can provide an example using AngularJS and KnockoutJS.

AngularJS (1.x) uses a method known as dirty-checking. Although their implementation is a bit complex, dirty-checking itself is a very simple concept.

AngularJS has a concept known as a digest cycle. During this digest cycle, AngularJS looks at objects on its application model known as $scope. It basically looks and says, "Ok, did this object change? It did. Ok, let's update the view. Did this object change? No. Ok, I'll move on and check the next object".

Although this works well in most applications, you can see how performance could be affected as we add more and more objects to the application model.

The other common way JavaScript frameworks such as KnockoutJS update only what's necessary is via the Observer pattern. In KnockoutJS, this works because all objects on the view-model are declared as observables. Therefore when the object on the view-model (subject) is changed, it fires off an event notification to it's "observers" which ends with the result of the view being updated.

Although this also works well in most applications, performance can be affected in this scenario too. Since you're basically wrapping each object on the view-model with an observable, all objects now have more overhead.

Too answer your main question, there really is no "best practice" for how JavaScript frameworks choose to do this. Like most things in the software world, there are trade-offs with either option.

Ben
  • 2,441
  • 1
  • 12
  • 16