Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS proper way to update observableArray AJAX

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.

like image 200
farina Avatar asked Mar 19 '12 17:03

farina


1 Answers

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.

like image 154
RP Niemeyer Avatar answered Nov 09 '22 07:11

RP Niemeyer