Initialize a KnockOut model with json
I want to init a Knockout model with as json received from the server.
For the moment, I have this html :
<div class='liveExample'>
<p>First name: <input data-bind='value: firstName' /></p>
<p>Last name: <input data-bind='value: lastName' /></p>
<h2>Hello, <span data-bind='text: fullName'> </span>!</h2>
</div>
And this JavaScript :
// Here's my data model
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
return this.firstName() + "/" + this.lastName();
}, this);
};
var viewModel = new ViewModel();
data = { firstName: 'test', lastName: 'bla' }; //received from the server
side
viewModel.firstName(data.firstName)
viewModel.lastName(data.lastName)
ko.applyBindings(viewModel);
It works, but if I have more fields, it can painful.
I tried to use the mapping plugin like this :
var viewModel = new ViewModel();
data = { firstName: 'test', lastName: 'bla' }; //received from the server
side
viewModel = ko.mapping.fromJSON(data, viewModel)
ko.applyBindings(viewModel);
In this case, the method fullName is undefined.
I tried to do this :
viewModel = ko.mapping.fromJSON(viewModel, data)
And the lastName and firstName are undefined.
Is there a simple solution to do this?
Thanks!
No comments:
Post a Comment