How to add array of objects into observable array in knockout?

こ雲淡風輕ζ 提交于 2019-12-22 04:42:25

问题


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);
            });
        };

回答1:


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.



来源:https://stackoverflow.com/questions/16105059/how-to-add-array-of-objects-into-observable-array-in-knockout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!