如何在剔除中将对象数组添加到可观察数组中? [英] How to add array of objects into observable array in knockout?
问题描述
我正在通过ajax获取大量对象,如果该数组包含数据,那么它将被传递到我的viewmodel中的ImportObservableListItems:
I am getting a large array of objects through ajax and if the array has data then it will be passed to ImportObservableListItems in my viewmodel:
success: function (data) {
debugger
if (data.length > 0) {
ReadingList.ImportObservableListItems(data);
}
在视图模型中,我想将每个对象添加到一个可观察的数组中,但是我需要每个对象的属性是可观察的.但是,如果数组包含大量对象,则浏览器将崩溃.有什么办法可以防止它?
in the viewmodel I would like to add each object to an observable array but I need the properties of each object to be observable. however if the array contains a large number of objects then the browser crashes. is there any way I could prevent it?
self.ImportObservableListItems = function (data) {
$.each(data, function(index, item) {
var newListItem = {
MediaID: ko.observable(item.MediaID),
MediaName: ko.observable(item.MediaName),
MediaTypeID: ko.observable(item.MediaTypeID),
MediaTypeName: ko.observable(item.MediaTypeName),
Group1: ko.observable(item.Group1),
Group2: ko.observable(item.Group2),
Group3: ko.observable(item.Group3),
Group4: ko.observable(item.Group4),
Group5: ko.observable(item.Group5)
};
ReadingList.ReadingListItems.push(newListItem);
});
};
推荐答案
您可以通过一次推送所有项目(推送接受多个项目)来减少流失:
You can reduce the churn by pushing all the items at once (push accepts multiple items):
var items = $.map(data, function (item) {
return {
MediaID: ko.observable(item.MediaID),
MediaName: ko.observable(item.MediaName),
MediaTypeID: ko.observable(item.MediaTypeID),
MediaTypeName: ko.observable(item.MediaTypeName),
Group1: ko.observable(item.Group1),
Group2: ko.observable(item.Group2),
Group3: ko.observable(item.Group3),
Group4: ko.observable(item.Group4),
Group5: ko.observable(item.Group5)
};
});
ReadingList.ReadingListItems.push.apply(ReadingList.ReadingListItems, items);
添加完所有项目后,这只会导致仅发出一条通知,而不是每个项目一次.
This will cause only a single notification to go out when all the items have been added, instead of once per item.
这篇关于如何在剔除中将对象数组添加到可观察数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!