Initialize KnockOut model using json

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' }; //received from the server side viewModel = ko.mapping.fromJSON(data, viewModel) ko.applyBindings(viewModel); 

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!

+4
source share
3 answers

You need to use ko.mapping.fromJS() since you are working with a real JavaScript object.

The ko.mapping.fromJSON() method is designed to work with a JSON string. For instance:

 '{ "firstName": "test", "lastName": "bla" }' 
+4
source

if the data property name and the corresponding observable names viewModel are the same, you can use the following code.

 var viewModel = new ViewModel(); for(var prop in data) viewModel[prop](data[prop]); ko.applyBindings(viewModel); 
0
source

knockout only:

 var ViewModel = function(data) { var self = this; self.firstName = ko.observable(data.first); self.lastName = ko.observable(data.last); self.fullName = ko.computed(function() { return self.firstName() + "/" + self.lastName(); }); }; var data = {first: 'lorem', last: 'ipsum'}; ko.applyBindings(new viewModel(data)); 

knockout + ko.mapping

 var ViewModel = function(data) { var self = this; ko.mapping.fromJS(initData, {}, self); self.fullName = ko.computed(function() { return self.firstName() + "/" + self.lastName(); }); }; var data = {first: 'lorem', last: 'ipsum'}; ko.applyBindings(new viewModel(data)); 
0
source

Source: https://habr.com/ru/post/1498451/


All Articles