Replace all elements in Knockout.js observableArray

C.J. picture C.J. · Mar 15, 2012 · Viewed 13.9k times · Source

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?

Answer

RP Niemeyer picture RP Niemeyer · Mar 15, 2012

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.