I am trying to use knockout mapping, but it isn't working as I expected. Here I created simpliest fiddle i can and it's not working.
Am I missing something?
https://jsfiddle.net/p48d11j5/1/
function Model(){
var self = this;
self.Id = ko.observable(0);
self.Name = ko.observable("Default");
self.Visible = ko.observable(false);
self.Items = ko.observableArray([]);
}
function ModelItem(){
var self = this;
self.Id = ko.observable(0);
self.Name = ko.observable("Default item name")
}
var m = new Model();
ko.mapping.fromJS({
Id:1,
Name: "Test",
Visible: true,
Items: [
{
Id:1,
Name:"First"
},
{
Id:2,
Name:"Second"
}
]
}, m);
ko.applyBindings(m);
edit: I am working with nested arrays, so I added array
edit2: I want have models "typed" to use functions or ko.computed properties of them
If you call ko.mapping.fromJS
with two arguments :
ko.mapping.fromJS(data, mappedObject)
the second argument is a mappedObject
which is already created.Then the second argument will be taken as a viewModel
not options
.
All you have to do is: ko.mapping.fromJS(data, {}, viewModel) - this one puts your data in your model.
ko.mapping.fromJS({
Id:1,
Name: "Test",
Visible: true,
Items: [{Id: 1, Name: "First"}, {Id: 2, Name: "Second"}]
}, {} ,m); // pass the second argument as an empty object.