我一直在使用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>
答案 0 :(得分:0)
您将JSON数据作为字符串传递到f
函数,而不是javascript对象。因此,您需要使用ko.mapping.fromJSON
代替ko.mapping.fromJS
。