我有以下 JSON 数据:
var donutData = [ {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping":
[
{ "id": "5001", "type": "None", "price": 45.00 },
{ "id": "5002", "type": "Glazed", "price": 45.00 },
{ "id": "5005", "type": "Sugar", "price": 45.00 },
{ "id": "5007", "type": "Powdered Sugar", "price": 45.00 },
{ "id": "5006", "type": "Chocolate with Sprinkles", "price": 45.00 },
{ "id": "5003", "type": "Chocolate", "price": 45.00 },
{ "id": "5004", "type": "Maple", "price": 45.00 }
]
},
{ "id": "0002",
"type": "donut",
"name": "Lava Cake",
"ppu": 0.65,
"topping":
[
{ "id": "5001", "type": "None", "price": 45.00 },
{ "id": "5002", "type": "Glazed", "price": 45.00 },
{ "id": "5005", "type": "Sugar", "price": 45.00 },
{ "id": "5007", "type": "Powdered Sugar", "price": 45.00 },
{ "id": "5006", "type": "Chocolate with Sprinkles", "price": 45.00 },
{ "id": "5003", "type": "Chocolate", "price": 45.00 },
{ "id": "5004", "type": "Maple", "price": 45.00 }
]
}
]
我可以使用以下命令轻松地将其数据绑定到我的 HTML 页面:
var DonutViewModel = function(){
donuts = ko.observableArray();
}
$(document).ready(function () {
ko.applyBindings(DonutViewModel(donutData));
});
这是我的 HTML:
<tbody data-bind="foreach:donuts">
<tr>
<td data-bind="text:id"></td>
<td data-bind="text:type"></td>
<td data-bind="text:name"></td>
<td data-bind="text:ppu"></td>
<td>
<table>
<tbody data-bind="foreach:topping">
<tr>
<td data-bind="text:type"></td>
</tr>
</tbody>
</table>
</td>
<td>
<table>
<tbody data-bind="foreach:topping">
<tr>
<td data-bind="text:price"></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
现在我想使用淘汰映射插件来完成同样的任务。我尝试了以下方法:
$(document).ready(function () {
var viewModel = ko.mapping.fromJS(donutData);
ko.applyBindings(viewModel());
//ko.applyBindings(DonutViewModel(donutData));
});
这给了我一个错误 - 显然,因为我使用了 data-bind="foreach:donuts" ,它不再存在于我的视图模型中。那么如何更改我的 UI 或数据来工作呢?
另外,在使用映射插件时,说我想在甜甜圈数据中添加一个新对象,我该怎么做?