I want to initialize a knockout model using json received from server.
At 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 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 be painful.
I tried using the display plugin as follows:
var viewModel = new ViewModel(); data = { firstName: 'test', lastName: 'bla' };
In this case, the fullName method is undefined.
I tried to do this:
viewModel = ko.mapping.fromJSON(viewModel, data)
Both lastName and firstName are undefined.
Is there a simple solution for this?
Thanks!
source share