Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all elements in Knockout.js observableArray

I have an observableArray in my view model. After creating the vm I wish to completely replace the data the observableArray. Here's how I'm doing it:

//Initial Setup var vm = {}; vm.roles = ko.observableArray([]); ko.applyBindings(vm);    //....replace array later on.... vm.roles(["1", "2"]); 

This seems to be working fine, but I was concerned if this was incorrect and might lead to memory leaks. Can anyone conform if this is the preferred way to update an existing observableArray assuming you wish to replace all its data?

I noticed observableArray does have a removeAll() method and wondered if that needed to be called to do this cleanly, or if I'm fine with what I'm doing?

like image 365
C.J. Avatar asked Mar 15 '12 08:03

C.J.


People also ask

How do you update items in observableArray knockout?

You should look at defining the object structure for each element of your array and then add elements of that type to your observable array. Once this is done, you will be able to do something like item. productQuantity(20) and the UI will update itself immediately. EDIT Added the function provided by the OP :).

What is Ko observableArray?

If you want to detect and respond to changes of a collection of things, use an observableArray . This is useful in many scenarios where you're displaying or editing multiple values and need repeated sections of UI to appear and disappear as items are added and removed.

What is an observable array?

An observable of arrays is a stream of arrays, each "tick" yielding a entire, new, different array. Therefore, use an array if you just want a list of items sitting there. Of course you can mutate or transform the array, but that doesn't change the fact that at any given point in time there is just one single array.


Video Answer


1 Answers

The technique that you are using is the recommended approach for completely replacing the data in an observableArray. An observableArray is actually just a normal observable with extra functions added for useful array operations that act on the underlying array and trigger notifications.

like image 55
RP Niemeyer Avatar answered Sep 19 '22 20:09

RP Niemeyer