Search code examples
javascriptarraysractivejs

What is the most efficient way to update an array with objects without re-rendering the entire DOM in RactiveJS?


If I have an array with objects in them.

var tableAry = [
  { id:0, name:"Bob"},
  { id:1, name:"Tim"},
  { id:2, name:"Pete"},
];

And I want to update Tim to be "Tim Smith".

tableAry[1] = { id:1, name:"Tim Smith"};

How do I do this without having to reset the whole array?

ractive.set("table",tableAry);

Wouldn't that force the whole table to be re-rendered?


Solution

  • Target the set to as specific a keypath as possible:

    // single property
    ractive.set("table.1.name", "Tim Smith");
    
    // multiple properties in one go:
    ractive.set({
        "table.1.name": "Tim Smith",
        "table.1.age": 12,
    });
    
    // you can update the object
    var item = ractive.get('table.1');
    item.name = 'Tim Smith';
    item.age = 22;
    ractive.set("table.1", item);
    

    That being said, Ractive has some smarts about not re-rendering things of the same value. Though it still has to do more comparisons.