I know this was asked multiple times already, but none of that answered my question. I have the following: I get data over JSON to Javascript into a two dimensional array. When I load the site, the table shows up like wanted. Now when I click a button (just for testing), it is updating one value from the array and logging that array in the console, where I see the changed array. The problem is that the change is not showing up in the table. When I just add a value to the array, it is showing up in the table. What am I doing wrong?
HTML:
<table id="sortsTable">
<tbody data-bind="foreach: sorts">
<tr>
<td data-bind="text: $data.name"></td>
<td data-bind="text: $data.ingName"></td>
</tr>
</tbody>
</table>
<button data-bind="click: addPerson">Add</button>
JS:
var sorts = ko.observableArray([]);
$(function() {
var request = new XMLHttpRequest();
var formData = new FormData();
var responseElements = [];
request.open("POST", "scripts.php", true);
formData.append("action", "getSorts");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
responseElements = JSON.parse(request.responseText);
sorts = convertList(responseElements);
ko.applyBindings(new AppViewModel(sorts));
}
}
request.send(formData);
});
function convertList(response) { //just the function to convert the json object to a more useful array
var names = [];
var ingredients = [];
var sorts = [];
for (var index = 0; index < response.length; index++) {
var name = response[index]['name'];
var ing = response[index]['ingName'];
if (names.indexOf(name) == -1) {
names.push(name);
}
if (ingredients.indexOf(ing) == -1) {
var nameIndex = names.indexOf(name);
if (ingredients[nameIndex] == undefined) {
ingredients[nameIndex] = ing;
} else {
ingredients[nameIndex] = ingredients[nameIndex] + ", " + ing;
}
}
}
for (var i = 0; i < names.length; i++) {
sorts[i] = {};
sorts[i]['name'] = names[i];
sorts[i]['ingName'] = ingredients[i];
}
return sorts;
}
function AppViewModel(data) {
var self = this;
self.sorts = data;
self.addPerson = function() {
console.log("click");
self.sorts[0]["name"] = "test"; //doesn't update table
//self.sorts.push({name: "qwer", ingName: "we"}); //works like expected
console.log(self.sorts);
};
}
Thanks.