问题
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?
回答1:
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.
回答2:
I found that the recommended approach does not work in IE9 or lower. Instead I had recreate the object,
vm.roles = ko.observableArray(["1","2"])
来源:https://stackoverflow.com/questions/9715936/replace-all-elements-in-knockout-js-observablearray