I'm working with knockoutjs and I'm trying to populate ViewModel instance from JSON data. According to knockoutjs documentation I may use this statement:
ko.mapping.fromJS(data, viewModel);
Here is my code :
var pledgeVM=function(){
this.name=ko.observable();
this.Assets=ko.observableArray([]);
this.StartEdit=function(assetModel){
};
};
pledge = {"name":"Moses","Assets":[{"CityId":13,"commetns":null},{"CityId":14,"commetns":null}]};
var pledgeVMinstance=new pledgeVM();
ko.mapping.fromJS(pledge,pledgeVMinstance);
For some reason data not populated (pledgeVMinstance.name()
is undefined)
unless I change the statement to:
ko.mapping.fromJS(pledge,{},pledgeVMinstance);
Maybe somebody can explain me why things going that way.
It happened because ko.mapping.fromJS
has the following signature:
ko.mapping.fromJS(data, mappingOptions, viewModel);
Where data
- is your json data, mappingOptions
- is the instructions to mapping plug how to map your date, viewModel
- is object to store mapped data.
ko.mapping.fromJS(data)
- this syntax will create view model.
ko.mapping.fromJS(data, mappingOptions
) - this will create view model with particular options.
ko.mapping.fromJS(data, {}, viewModel)
- and this one convers your data without mapping options and put it to view model.
Read the documentation for better understanding: http://knockoutjs.com/documentation/plugins-mapping.html