Reputation: 1058
I have a ko.observablearray.I'm populating with some values I get from the server:
self.AllItems = ko.observableArray([]);
$.getJSON('/Controller/GetItems', function (data) {
for (var index = 0; index < data.length; index++) {
self.AllItems.push(data[index]);
}
};
});
I know this much works fine as I have the array bound to list and that contains all the items.
<select multiple="multiple" size='4' data-bind="options:$root.AllItems, selectedOptions:$root.ItemsSelectValue"> </select>
However, I'm not able to access any of the elements of AllItems afterwards.
alert(self.AllItems().length);
-- returns 0
alert(self.AllItems());
-- returns nothing
Please help.
Upvotes: 1
Views: 788
Reputation: 4228
You are likely trying to alert the value of AllItems
before the (asynchronous) jQuery Ajax call has completed. You can get around this by making use of jQuery XHR promises, such as the done
promise:
self.AllItems = ko.observableArray([]);
// Perform the XMLHttpRequest, and store the XHR object in a variable
var getItemsXHR = $.getJSON('/Controller/GetItems', function (data) {
for (var index = 0; index < data.length; index++) {
self.AllItems.push(data[index]);
}
});
// Wait for the XMLHttpRequest to finish before reading AllItems
getItemsXHR.done(function(data, textStatus, jqXHR) {
alert(self.AllItems().length);
alert(self.AllItems());
});
Upvotes: 1