Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize Knockout ViewModel with json data before apply binding best practices [closed]

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.

like image 219
ebram khalil Avatar asked Nov 13 '22 02:11

ebram khalil


1 Answers

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.

like image 83
Jeroen Avatar answered Nov 14 '22 23:11

Jeroen