javascript 替换 Knockout.js observableArray 中的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9715936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace all elements in Knockout.js observableArray
提问by C.J.
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:
我的observableArray
视图模型中有一个。创建 vm 后,我希望完全替换observableArray
. 这是我的做法:
//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?
这似乎工作正常,但我担心这是否不正确并可能导致内存泄漏。如果这是更新现有observableArray
数据的首选方式(假设您希望替换其所有数据),那么任何人都可以同意吗?
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?
我注意到observableArray
确实有一种removeAll()
方法,并想知道是否需要调用它才能干净利落地做到这一点,或者我是否对我正在做的事情感到满意?
采纳答案by RP Niemeyer
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.
您使用的技术是完全替换observableArray
. AnobservableArray
实际上只是一个普通observable
函数,为有用的数组操作添加了额外的函数,这些函数作用于底层数组并触发通知。
回答by user887
I found that the recommended approach does not work in IE9 or lower. Instead I had recreate the object,
我发现推荐的方法在 IE9 或更低版本中不起作用。相反,我重新创建了对象,
vm.roles = ko.observableArray(["1","2"])