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?
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 :).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With