Replace all elements in Knockout.js observableArray
Asked Answered
C

2

45

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?

Conga answered 15/3, 2012 at 8:9 Comment(0)
A
42

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.

Asiatic answered 15/3, 2012 at 11:21 Comment(1)
When you say "the recommended approach" my training from answering questions on skeptics.stackexchange.com kicks in. Would you happen to have supporting documentation/links for your statement? [ with respect, of course; you are Mr. Knockmeout himself (O; ]Doorjamb
Q
-6

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"])
Qoph answered 19/9, 2013 at 16:27 Comment(2)
I wonder if that has changed with newer versions of Knockout... What version were you using?Tenuous
If you replace the entire object, observers won't be notified, correct?Kosiur

© 2022 - 2024 — McMap. All rights reserved.