1
如何從通過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>
http://jsfiddle.net/atwoodkevin/q8EKP/40/