我是knockout.js的新手,需要对如何使用json数据更新表单字段有一个非常基本的了解。我有一个viewmodel。如何将json数据拉入可观察字段?
<p>Errors: <input data-bind="value: errors" /></p>
<p>Message: <input data-bind="value: message" /></p>
// Here's my data model
var ViewModel = function(myError, myMessage) {
this.errors = ko.observable(myError);
this.message = ko.observable(myMessage);
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work
$.getJSON("http://api.twitter.com/1/statuses/public_timeline.json", function(data) {
})
答案 0 :(得分:1)
我更喜欢明确地设置视图模型属性 - 我觉得它更容易控制和维护。
var ViewModel = function(myError, myMessage) {
var self = this;
self.errors = ko.observable(myError);
self.message = ko.observable(myMessage);
self.property1 = ko.observable();
self.property2 = ko.observable();
};
var vm = new ViewModel("Planet", "Earth");
ko.applyBindings(vm); // This makes Knockout get to work
$.getJSON("http://api.twitter.com/1/statuses/public_timeline.json", function(data) {
vm.property1(data.field1);
vm.property2(data.field2);
...etc
})
如果这看起来过于冗长,那么您还可以使用映射插件将JSON中的值自动映射到视图模型中。
在此处详细了解:http://knockoutjs.com/documentation/plugins-mapping.html
var vm = new ViewModel("Planet", "Earth");
ko.applyBindings(vm); // This makes Knockout get to work
$.getJSON("http://api.twitter.com/1/statuses/public_timeline.json", function(data) {
var jsObject = ko.fromJSON(data);
ko.mapping.fromJS(jsObject , viewModel);
})