我使用Knockout.js已经有一段时间了,现在正在调整页面以从服务器读取json。它一直在工作,直到我改用knockout.mapping(以使事情更简单)。
它渲染(仅一次)
â¦
<p>hello <span data-bind="text: name"></span></p>
â¦
在chrome调试器中,我看到
viewModel.rows()
是
Array[4]
,但4个对象显示为空。
怎么了?
<!DOCTYPE html>
<html>
<head></head>
<body>
<div data-bind="foreach: rows">
<!-- ko with: value -->
<p>hello <span data-bind="text: name"></span></p>
<!-- /ko -->
</div>
</body>
<script src="script/knockout-3.0.0.js"></script>
<script src="script/knockout.mapping-2.4.1.js"></script>
<script>
var viewModel = null;
function load(){
f = function(data) {
if (viewModel == null){
viewModel = ko.mapping.fromJSON(data);
}else{
ko.mapping.fromJSON(data,viewModel);
}
};
f(
'{
"total_rows" : 4,
"rows" : [
{
"value" : {
"_id" : "e47b7701-cb51-4746-a02b-8a5203afa0a5",
"name" : "alice",
"_rev" : "13-327c79c92082537f7764b3d5601f1829"
},
"id" : "e47b7701-cb51-4746-a02b-8a5203afa0a5",
"key" : 50
},
{
"value" : {
"_id" : "f450ccc5-3132-41a3-ade7-193d100e035b",
"name" : "bob",
"_rev" : "13-36dcb1ec370bcc27507b7d78ad66a5eb"
},
"id" : "f450ccc5-3132-41a3-ade7-193d100e035b",
"key" : 100
},
{
"value" : {
"_id" : "c5bf17ce-f482-4bd7-a6c4-1b098aa213f8",
"name" : "clare",
"_rev" : "7-7b6acade5106e4b064249e7446dbc451"
},
"id" : "c5bf17ce-f482-4bd7-a6c4-1b098aa213f8",
"key" : "0"
}
],
"offset" : 0
}'
);
}
load();
ko.applyBindings(viewModel);
</script>
</html>