我想用从服务器接收到的 json 来初始化一个 Knockout 模型。
目前,我有这个 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>
而这个 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);
它有效,但如果我有更多的领域,它可能会很痛苦。
我尝试像这样使用映射插件:
var viewModel = new ViewModel();
data = { firstName: 'test', lastName: 'bla' }; //received from the server side
viewModel = ko.mapping.fromJSON(data, viewModel)
ko.applyBindings(viewModel);
在这种情况下,方法fullName
是未定义的。
我试图这样做:
viewModel = ko.mapping.fromJSON(viewModel, data)
并且lastName
andfirstName
是未定义的。
有没有一个简单的解决方案来做到这一点?
谢谢!