如何从通过 Ajax 返回的 JS 对象构建动态视图模型?
在创建可观察对象和可观察数组时,视图不包含任何数据,除非每次获取后绑定,导致多次绑定警报。
我的JS
var SummaryData = {
Summary: {
Count: 4
}
};
var DetailsData = {
Status: [{
Name: "One",
Type: 1
}, {
Name: "Two",
Type: 1
}, {
Name: "Three",
Type: 0,
Taco: "True"
}]
};
var self = this;
self.Summary = new ko.observableArray([]);
self.Details = ko.observable();
self.Load = function () {
$.ajax({
url: "/echo/json/",
data: SummaryData,
type: "GET",
success: function (data) {
// Map the returned JSON to the View Model
self.Summary = ko.mapping.fromJS(data.Summary);
}
})
$.ajax({
url: "/echo/json/",
data: DetailsData,
type: "GET",
success: function (data) {
// Map the returned JSON to the View Model
self.Details = ko.mapping.fromJS(data.Status);
}
})
我的 HTML:
<span data-bind="text: Summary.Count"></span>
<table data-bind="foreach: Details">
<tr>
<td data-bind="text: Name"></td>
<td><button data-bind="click: $root.Clicked"></button></td>
</tr>
</table>