I have a simple knockoutjs ViewModel. but before i apply binding from that model to my view i need first to initialize it or set array value with some data (JSON format) that i 'll get from the server via AJAX.
I know i can create object of my model, make the ajax request then initialize my model array. Like this:
function AppViewModel() {
var self = this;
self.Servers = ko.observableArray([]);//this one 'll be filled by data from server
}
var MyViewModel = new AppViewModel();
MyViewModel.Servers = ko.mapping.fromJSON(json_data);//make ajax call to get json_data.
ko.applyBindings(MyViewModel);
Is that good practice or there is better one.
Seems like a fine way to do it to me, at least with the context you're providing. The mapping plugin's documentation has a section about AJAX requests, and also concludes with an "advanced" section that helps you track the keys of server objects so that posting back updates to the server gets easier.
Another good source is the loading & saving tutorial. It doesn't use the mapping plugin, showing the more basic things about handling CRUD operations through AJAX requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With