here is my viewModel:
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:
AJAX Call
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:
Mapping
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);
};
And the same for the other array.
Now here is my data binding:
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>
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?
I found the problem.
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.
What happens if you try:
There's no mention of what the variables you were pre-populating the arrays with are.
Then add each item to your observable directly: