Hello I have the following code which uses knockout.js,
var allJobberDetailsArray = [];
getAllJobberDetailsArray();
function getAllJobberDetailsArray() {
$(function() {
$.ajax({
url: 'http://example.com',
type: 'GET',
data: {
request: "yes",
getAllJobberDetailsArray: "yes"
},
success: function(data) {
allJobberDetailsArray = data;
}
});
})
}
// ViewModel
function JobberCheckBoxListUserControlViewModel() {
var self = this;
self.allJobberDetailsArray = ko.observableArray(allJobberDetailsArray);
}
ko.applyBindings(new JobberCheckBoxListUserControlViewModel());
any change to allJobberDetailsArray I would like to update the UI automatically say an array item is added updated or deleted i would like the UI to reflect it.
How do i achieve it?
EDIT
var allJobberDetailsArray = ko.observableArray();
getAllJobberDetailsArray();
function getAllJobberDetailsArray() {
$(function() {
$.ajax({
url: 'http://example.com',
type: 'GET',
data: {
request: "yes",
getAllJobberDetailsArray: "yes"
},
success: function(data) {
allJobberDetailsArray.removeAll();
allJobberDetailsArray.push(data);
},
});
})
}
// ViewModel
function JobberCheckBoxListUserControlViewModel() {
var self = this;
self.allJobberDetailsArray = allJobberDetailsArray;// allJobberDetailsArray is now observable but any change to this doesn't reflect in the UI
}
var viewModel = new JobberCheckBoxListUserControlViewModel();
ko.applyBindings(viewModel);
in the above code i made the array itself observable and trying to auto update the UI if there are any changes to the array how do i achieve it?
Firstly the array you are updating isn’t an observable array. Secondly your success callback actually overwrites the array. Finally you do not keep a reference to your viewModel so you are unable to properly update the observable array. ObservableArray wrap real arrays to make them observable. All add’s removes etc need to go through the observableArray so the subscribers can be notified.
Try this instead.
I would also recommend refactoring to put the
getAllJobberDetailsArraymethod inside your viewModel so it doesn’t polute the global namespace and maintains encapsulation.Hope this helps.