来自ObservableArray的数据在我的表中显示两次 [英] Data coming from an ObservableArray are displayed twice in my table
问题描述
这是我的viewModel:
here is my viewModel:
var sitesTableModel = [
{
nameCol: "nameCol-1",
pagesCol: "pagesCol-1",
},
{
nameCol: "nameCol-2",
pagesCol: "pagesCol-2",
}];
var pagesTableModel = [
{
lastCol: "lastCol-1",
editedCol: "editedCol-1",
},
{
lastCol: "lastCol-2",
editedCol: "editedCol-2",
}];
var viewModel = {
sitesTable: ko.observableArray(sitesTableModel),
pagesTable: ko.observableArray(pagesTableModel),
};
然后我以这种方式调用网络服务:
then I call a webservice in this way:
ajaxService = (function () {
var ajaxGetJson = function (method, request, callback, service) {
$.ajax({
url: "http://localhost:2880/Whatever.svc/Method",
type: "GET",
data: request,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result, statusMsg, status)
{
callback(result, statusMsg, status, request);
},
error: ServiceFailed
}).always(function () {
ko.applyBindings(viewModel);
});
}
return {
ajaxGetJson: ajaxGetJson,
};
})();
并以这种方式映射结果:
and map the result in this way:
function ModelTableSitesMapper(result, statusMsg, status, request) {
var itemRow = [];
//sitesTableModel
result.forEach(function (entry) {
itemRow.push({
nameCol: entry.Title,
pagesCol: entry.Pages,
})
});
viewModel.sitesTable = ko.observableArray(itemRow);
};
与其他数组相同.
现在这是我的数据绑定:
Now here is my data binding:
<table id="tableDocs">
<tbody data-bind="foreach: documentsTable" >
<tr>
<td data-bind="text: nameCol">Simon Werner Hansen</td>
<td data-bind="text: pagesCol">swh002</td>
</tr>
</tbody>
</table>
当我得到结果时,表中的所有内容都被分配了两次. 我检查了模型,并且observableArray中没有重复数据. 我知道我两次将对象声明为observableArray,这可能是问题所在,但我无法找到其他任何方式来更新数组:
and when I get the result everything is dispoayed twice in the table. I checked the model and there is no double data in the observableArray. I know Iøm declaring the object as observableArray twice, and that could be the problem but I canøt find any other way to update the array than this:
viewModel.sitesTable = ko.observableArray(itemRow);
如果我这样做应该是行不通的:
if I do this as it should be it just does not work:
viewModel.sitesTable(itemRow);
也许有人可以理解这的原因吗?
Maybe somebody could understand there reason for this?
推荐答案
我发现了问题.
我在ajax调用的 .always 函数上应用了绑定ko.applyBinding,但是由于两次原因,我两次调用了该服务,因此应用了绑定 TWICE 强>. 这导致数据重复.
I was applying the binding ko.applyBinding on the .always function of the ajax call, but because I was calling the service twice for 2 different reasons the binding was applied TWICE. That caused the duplication of data.
创建模型后,我只是将绑定移到了函数之外.
I just moved the binding outside the function just after I create my model.
这篇关于来自ObservableArray的数据在我的表中显示两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!