KnockoutJS is the proper way to update an observable AJAX array

In KnockoutJS, what is the correct way to update a monitored JSON dataset every time I execute an AJAX command?

Right now I'm quenching an array using something like viewmodel.items ([]) and then re-populating it with JSON data from the server. If you are not using the KnockoutJS mapping plugin (which may be the only way to do this), what is the correct way?

My server logic is going to send the same data every time, so I can’t just iterate over and move items to an array if I don't want duplicates.

//// Adding how I do it today ////

I'm not sure why I am doing this, but this is exactly how I initially understood how to update. So basically, as I said, I get the JSON data, then pass it 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 have some custom watch elements that are collected with each data transfer. Perhaps this is the wrong way, but so far it has worked perfectly.

+6
source share
2 answers

An observable array is indeed a normal observable with some additional methods for operations with arrays.

So, if you want to set the value of the observed array to a new array, you can simply do:

viewModel.items(myNewArray)

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

+10
source

I know that I am too late in this, since I found myself in this situation quite recently. We can use the simple function of using JavaScript as a workflow.

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

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

It worked for me. Hope you created your observation as follows:

 _model.incidents = ko.observableArray([]); 
-1
source

Source: https://habr.com/ru/post/911122/


All Articles