Add multiple items to an observableArray

3,808 views
Skip to first unread message

Johan Seppäläinen

unread,
Apr 27, 2011, 7:15:35 PM4/27/11
to KnockoutJS
I have a template bound to an observableArray. Occasionally I need to
add a whole bunch of items to the array. Now I add those items one by
one with push() but it takes way too long time. Guess it is because
the list is re-rendered for every push.
Just for reference I instead pushed the items to another
observableArray that was not bound to a template, and that operation
was really quick in comparison.

So, is there a way to add multiple items without re-rendering the
template for every item?

Joel Dart

unread,
Apr 27, 2011, 9:35:26 PM4/27/11
to KnockoutJS
get the latest value of the array, add your items to that, and then
assign that back to the observableArray. http://jsfiddle.net/JVEQX/
the change tracking in ko is sophisticated enough to handle those
types of changes without needing to rerender, in fact, even if you
used a new array and copied from one array to another, it sees the
objects are the same and just rerenders the new ones

Joel Dart

unread,
Apr 27, 2011, 10:19:34 PM4/27/11
to KnockoutJS
Also, you can use the splice array operator on observable arrays
(works just like with regular js arrays) to insert at the beginning of
the array or anywhere you want. http://jsfiddle.net/JVEQX/2/

I feel splice is a bit messy, though powerful, so I broke out the
insertAt method to make the logic a bit more clear. Hope this helps

rpn

unread,
Apr 27, 2011, 11:40:48 PM4/27/11
to knock...@googlegroups.com
One other thing to add based on the original question.  If you are regularly going to be adding/removing items from your observableArray and you are using a template to render it, make sure that you are using the "foreach" option of the template binding, as opposed to jQuery Template's {{each}} tag.  It sounds like maybe you were using {{each}} based on your experience.  In that case, your entire template will get re-rendered on every change to the array (so, all items get re-rendered).  With the "foreach" option, only the item or items that were added to your array will be rendered.  The docs explain it better here.

So, you can certainly use the techniques that Joel mentioned to join the original array with your new items, but normally if you are using the "foreach" option you won't see a huge benefit by adding them all at once.



Johan Seppäläinen

unread,
Apr 28, 2011, 3:56:28 PM4/28/11
to KnockoutJS
Excellent info. Totally missed the important stuff about the foreach
option...
Big thanks to both of you.
Reply all
Reply to author
Forward
0 new messages