我是 javascript/jquery 的新手,正在学习 knockoutjs。我被困在这个问题上。我的页面中有两个 ko 绑定。第一个创建一个链接,用户可以单击该链接以查看有关该项目的更多信息。该链接包含一个传递给 ajax 调用的 ID,该调用将数据返回给第二个 ko observable。
问题是第二个可观察数据总是在页面上显示为“未定义”。然而,如果我在创建 observable 的代码中放置一个 console.log(data),数据就在那里。同样,在 Fiddler 中,ajax 调用请求的 json 被很好地发回。
我确信这与我绑定可观察对象的方式有关,但我尝试了几种不同的方法(使用数组、不使用数组等)但无济于事。任何帮助或指示将不胜感激。似乎是一个简单的问题,但我已经尝试了一切,但无法让它工作......
$(document).ready(function () {
var da = new firstViewModel();
ko.applyBindings(da, document.getElementById('da'));
var eq = new secondViewModel();
//Binding the second observable here but not using it yet as it depends on getting data from the //first (da) in order to work.
ko.applyBindings(eq, document.getElementById('eqdetails'));
});
function da(data) {
var self = this;
self.eqid = ko.observable(data.eqid);
self.modelname = ko.observable(data.modelname);
}
function firstViewModel() {
// Data
var self = this;
self.da = ko.observableArray([]);
self.getdetails = function (da) {
selectedid = da.eqid();
//Call second observable when user clicks on link.
var eq = new secondViewModel();
eq.geteqdetails();
}
};
};
function eqview(data) {
console.log('in eqview ' + data); //This works, but data is still undefined in html
var self = this;
self.modelname = ko.observable(data.modelname);
self.number = ko.observable(data.number);
};
function secondViewModel() {
var self = this;
self.eqviews = ko.observableArray([]);
self.geteqdetails = function () {
$.ajax("../Process/GetEqDetails", {
type: "post",
contentType: "application/json",
data: JSON.stringify({ EqID: selectedid }),
success: function (result) {
console.log('in ajax call ' + result.data);
var mappedequipmentview = $.map(result, function (item) { return new eqview(item) });
self.eqviews(mappedequipmentview);
}
});
};
这是页面的 HTML:
<div id="da" class="span3">
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Model</th>
<th>ID</th>
</tr>
</thead>
<tbody data-bind="template: { name: 'datemplate', foreach: da }">
</tbody>
</table>
<script id="datemplate" type="text/html">
<tr>
<td><span data-bind="text: modelname"></span></td>
<td>
<button type="button" class="btn btn-link" data-bind="click: $root.getdetails" title="View">
<span data-bind="text: eqid"></span></button>
</td>
</tr>
</script>
</div>
<div class="span6">
<div class="span1">
<table class="table table-bordered table-condensed" id="eqdetails">
<tbody >
<tr>
<td><span data-bind="text: $data.modelname "></span></td>
</tr>
<tr>
<td><span data-bind="text: $data.number "></span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>