Nikita  Fedorov Nikita Fedorov - 1 month ago 9
Javascript Question

Knockout js observableArray is not getting updated

I'm trying to update the observable array from the response data.
I'm sure I've missed something simple, but I can't find out why it doesn't work?



function addWitness() {

$.post("AddWintess", {
Witnesses: [{
LastName: "test1",
FirstName: "test1",
MiddleName: "test1"
}, {
LastName: "test2",
FirstName: "test2",
MiddleName: "test2"
}]
}, function(data) {
my.viewModel.allItems = ko.observableArray(data.Witnesses);
});
}
var my = {
viewModel: new WitnessesModel()
}

function WitnessesModel() {
var self = this;
self.allItems = ko.observableArray([]);
self.test = ko.computed(function() {
var result = "";
self.allItems().forEach(function(item) {
result += item + "; ";
});
});
}
ko.applyBindings(my.viewModel);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<ul data-bind="foreach: allItems">
<li data-bind="text: FirstName"></li>
</ul>
<input type="button" class="btn btn-success" value="+" onclick="addWitness()" />





I've set the breakpoints in the test function, but it's not getting fired.

Answer

Try this line my.viewModel.allItems(data.Witnesses); instead of

my.viewModel.allItems = ko.observableArray(data.Witnesses);