KnockoutJS适当的方式来更新observableArray AJAX [英] KnockoutJS proper way to update observableArray AJAX

查看:351
本文介绍了KnockoutJS适当的方式来更新observableArray AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在KnockoutJS,什么是适当的方式每一个AJAX命令运行时间更新的JSON数据的observableArray?

In KnockoutJS, what's the proper way to update an observableArray of JSON data each time an AJAX command is run?

现在,我正在消隐使用类似viewmodel.items([])的阵列,然后从服务器的JSON数据重新填充它。短期使用KnockoutJS映射插件(这可能是做到这一点的唯一方法)什么是正确的道路?

Right now, I'm blanking the array using something like viewmodel.items([]), then repopulating it with the JSON data from the server. Short of using the KnockoutJS mapping plugin (which might be the only way to do this) what is the correct path?

我的服务器逻辑是要在每次发送一些相同的数据,所以我不能只是循环,推动项目成​​阵,除非我不想重复。

My server logic is going to send some of the same data each time, so I can't just iterate and push the items into the array unless I want duplicates.

////添加我今天怎么做////

//// Adding how I'm doing it today ////

我不知道我为什么做这种方式,但这是多么我最初想出如何更新。所以基本上,就像我之前说的,我得到的JSON数据,然后我把它传递给这样的:

I'm not sure why I'm doing it this way, but this is just how I initially figured out how to update. So basically, like I said before, I get JSON data, then I pass it to something like this:

    _model.addIncident = function (json) {
       var checked = json.UserTouches > 0 ? true : false;
       _model.incidents.push({
          id: ko.observable(json.IncidentIDString),
          lastTouchId: ko.observable(json.UserLastTouchIDString),
          weight: ko.observable(json.Weight),
          title: ko.observable(json.Title),
          checked: ko.observable(checked),
          createdOn: ko.observable(json.IncidentCreatedOn),
          servicename: ko.observable(json.Servicename),
          inEdit: ko.observable(false),
          incidentHistory: ko.observableArray(),
          matchScore: ko.observable()
      });
   };

有关JSON数组中的每个节点。正如你所看到的,我已经得到了在那里一些自定义的观测是得到建立,每过一段数据。也许这是错误的路要走,但它的工作太棒了到现在为止。

for each node in the JSON array. As you can see, I've got some custom observables in there that get build with every passing piece of data. Maybe this is the wrong way to go, but it's worked great up until now.

推荐答案

这是observableArray仅仅是一个正常的可观察与数组操作一些额外的方法。

An observableArray is really just a normal observable with some extra methods for array operations.

所以,如果你想要一个observableArray的值设置为一个新的数组,你可以这样做:

So, if you want to set the value of an observableArray to a new array, you can just do:

viewModel.items(myNewArray)

该映射插件可以帮助你更新的任何更新数组中的现有项目。在这种情况下,你的UI将只从任何差异更新。

The mapping plugin can help you update the existing items in an array with any updates. In this case, your UI will only be updated from any differences.

这篇关于KnockoutJS适当的方式来更新observableArray AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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