Reputation: 4247
I am fairly new to knockout and trying to figure out why the following won't work. For some reason my returned data from the ajax call is not being translated into an array.
I have a function that returns some JSON
bankingApi.client = (function () {
var getSafeFloatCash= function getSafeFloatCash() {
return $.ajax({
url: '/BackOffice/Banking/Banking/GetSafeFloat',
type: 'GET'
});
}
return {
getSafeFloatCash : getSafeFloatCash
};
})();
The function returns the following JSON:
[{"Denomination":"1p","Value":34.1200},{"Denomination":"2p","Value":98.0400},{"Denomination":"5p","Value":85.0500},{"Denomination":"10p","Value":571.2000},{"Denomination":"20p","Value":62.8000},{"Denomination":"50p","Value":57.5000},{"Denomination":"£1","Value":441.0000},{"Denomination":"£2","Value":398.0000},{"Denomination":"£5","Value":260.0000},{"Denomination":"£10","Value":320.0000},{"Denomination":"£20","Value":780.0000},{"Denomination":"£50","Value":350.0000}]
I set up my observable array
(function () {
var BankingViewModel = function () {
var self = this;
self.safeFloatDenominations = ko.observableArray();
var safeFloatCash = bankingApi.client.getSafeFloatCash();
self.safeFloatDenominations(safeFloatCash); // does not work!
self.safeTopUpValue = ko.computed(function () {
var total = self.floatRecommendedValue - self.safeFloatTotal;
return total.toFixed(0);
});
}
$(document).ready(function () {
var viewModel = new BankingViewModel();
ko.applyBindings(viewModel);
});
})();
If I paste the values returned from the ajax call into an array variable it works fine, so there is some issue translating the function call into an array.
and this is the view
<div class="row" data-bind="visible: safeTopUpValue()>0, foreach: safeFloatDenominations">
<div class="col-xs-5">
<input type="text" data-bind="value: Value" />
<label data-bind="text: Denomination"></label>
</div>
Upvotes: 0
Views: 403
Reputation: 32202
Building on my comment, $.ajax
doesn't return data - it returns a promise. You need to use that to actually get the data out:
var safeFloatCash = bankingApi.client.getSafeFloatCash();
safeFloatCash.done(function(d) {
//may need to parse the data:
//d = JSON.parse(d);
self.safeFloatDenominations(d);
});
Upvotes: 1