我想第一次使用 KnockoutJS 映射插件,因为它可以为我节省很多代码。但是尽管对象被映射,它并没有绑定到视图。我的代码如下:
JavaScript
...
//global variables
var mv;
...
function viewmodel() {
var self = this;
self.searchViewModel = ko.mapping.fromJS({});
}
...
//load function
$().ready(function () {
mv = new viewmodel();
doSearch();
ko.applyBindings(mv);
...
}
function doSearch() {
var params = "{'_search':'" + JSON.stringify(searchObject) + "'}";
$("#_pnlMachineList").mask("Loading...");
$.ajax({
type: "POST",
url: "machinepark2.aspx/doSearch",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
dataFilter: function(data) {
// This boils the response string down
// into a proper JavaScript Object().
var msg = eval('(' + data + ')');
// If the response has a ".d" top-level property,
// return what's below that instead.
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
success: function (msg) {
ko.mapping.fromJS(msg, {}, mv.searchViewModel);
},
error: function (msg) {
//document.location = "/errorPage.aspx";
}
});
}
HTML
Count: <span data-bind="text: searchViewModel.searchCount"></span>
<br />
<table class="table">
<thead>
<tr class="text_bold">
<th>Name</th>
<th>Type</th>
<th>Model</th>
</tr>
</thead>
<tbody data-bind="foreach: searchViewModel.machines">
<tr style="cursor:pointer;" data-bind="attr: { 'data-guid': GUID }, click: loadmachine">
<td data-bind="text: EndUserMachineName"></td>
<td><img alt="" style="position: relative;" data-bind="attr: { src: TypeImage }"></td>
<td data-bind="html: ManufacturerModel"></td>
</tr>
</tbody>
</table>
执行 doSearch 函数后,我可以在 firebug 控制台中查看 mv.searchViewModel。所有属性都很好地放入可观察对象中:
mv.searchViewModel.searchCount() 给了我一个整数:2。
但是计数标签和表格没有填写。我究竟做错了什么?
编辑:Firebug 没有给出任何错误。