KnockoutJS proper way to update observableArray AJ

2019-04-07 20:43发布

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

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 ////

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

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.

2条回答
Root(大扎)
2楼-- · 2019-04-07 21:07

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

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

viewModel.items(myNewArray)

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.

查看更多
SAY GOODBYE
3楼-- · 2019-04-07 21:32

I know I'm way too late on this one as I found myself stuck in this situation just recently. We can use a simple Javascript util function as a work-around.

If you have already marked _model.incidents as observableArray, you can do something like this when binding the returned JSON data:

eval("_model.incidents("+JSON.stringify(json)+");");

It worked for me. Hope you have created your observable like this:

_model.incidents = ko.observableArray([]);
查看更多
登录 后发表回答