Why can not I concat data to observable array in knockout

空扰寡人 提交于 2019-12-08 19:35:55

问题


I am trying to add elements from the server to observable array in knockout.

Here is my ViewModel:

function ArticlesViewModel() {
    var self                = this;
    this.listOfReports      = ko.observableArray([]);

    self.loadReports = function() {
        $.get('/router.php', {type: 'getReports'}, function(data){
            for (var i = 0, len = data.length; i < len; i++){
                self.listOfReports.push(data[i]);
            }
        }, 'json');
    };

    self.loadReports();
};

And it works perfectly. But I know that I can merge two arrays in javascript using concat() and as far as I know concat works in knockout. So when I try to substitute my for loop with self.listOfReports().concat(data); or self.listOfReports.concat(data); , nothing appears on the screen.

In the first case there is no error, in the second error tells me that there is no method concat.

So how can I concat the data without my loop. And I would be really happy to hear why my method was not working


回答1:


The observableArray does not support the concat method. See the documentation for the officially supported array manipulation methods.

However what you can do is to call concat on the underlying array and then reassign this the new concatenated array to your observable:

self.listOfReports(self.listOfReports().concat(data));

The linked example works because the self.Products().concat(self.Products2()) were used in a loop. If you just write self.listOfReports().concat(data); it still concatenates but you just thrown away the result and don't store it anywhere, that is why you need to store it back to your observableArray.



来源:https://stackoverflow.com/questions/21930955/why-can-not-i-concat-data-to-observable-array-in-knockout

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