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.
ko.mapping.fromJS(data, mappedObject)
where the second argument is a "mappedObject" which is already created by the mapping plugin (so it has the__ko_mapping__
property definied) it will treat the second argument as the viewModel and not as the options. See: github.com/SteveSanderson/knockout.mapping/blob/master/…. That is way in the documentation the update sampleko.mapping.fromJS(data, viewModel);
works. – Setup