为什么我无法在淘汰赛中将数据合并到可观察数组 [英] Why can not I concat data to observable array in knockout

查看:92
本文介绍了为什么我无法在淘汰赛中将数据合并到可观察数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从服务器中将元素添加到可剔除的可观察数组中.

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

这是我的ViewModel:

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

它运行完美.但是我知道我可以使用 concat可在淘汰赛中工作.因此,当我尝试用self.listOfReports().concat(data);self.listOfReports.concat(data);代替for循环时,屏幕上没有任何显示.

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.

在第一种情况下没有错误,在第二种错误告诉我没有方法concat.

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

推荐答案

observableArray 不支持concat方法.请参阅文档,以获取官方支持的数组操作方法.

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

但是,您可以做的是在基础数组上调用concat,然后将此新的级联数组重新分配给您可观察的数组:

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

链接的示例可以正常工作,因为self.Products().concat(self.Products2())在环形.如果您只写self.listOfReports().concat(data);,它仍然会串联,但是您只是丢弃结果,并且不将其存储在任何地方,这就是为什么您需要将其存储回observableArray的原因.

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.

这篇关于为什么我无法在淘汰赛中将数据合并到可观察数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆