I'm trying to receive data via AJAX and show it on the page. The ajax request is successful, but knockout doesn't update view. What can be the problem?
Source Code: View Model
class AppViewModel
constructor: ->
@company = ko.observable {name:'n/a', tariff:'n/a', contract:'n/a', balance:'0'}
@getBriefInfo()
@companyTariff = ko.computed => "Tariff: #{@company.tariff}"
@companyBalance = ko.computed => "Total: #{@company.balance}"
getBriefInfo: ->
$.ajax
type: 'POST'
url: '/index.php/site/getCompanyShortInfo'
data: {}
dataType: 'json'
contentType: 'json'
success: (res) =>
console.log @company(), res.name, res.tariff
@company res
console.log @company(), res.name, res.tariff
$ ->
ko.applyBindings(new AppViewModel(),document.getElementById("company-info"))
Source Code: View
<ul id="company-info" class="unstyled company-info">
<li data-bind="text: company.contract"></li>
<li data-bind="text: company.name"></li>
<li data-bind="text: companyBalance"></li>
<li data-bind="text: companyTariff"></li>
</ul>
The company property is observable, not its properties. Since you bind directly to the properties, you will not see any changes when the company object changes.
You may be able to get away with just making use of the with binding. When the company changes, the contents should update.
<ul id="company-info" class="unstyled company-info">
<!-- ko with: company -->
<li data-bind="text: contract"></li>
<li data-bind="text: name"></li>
<!-- /ko -->
<li data-bind="text: companyBalance"></li>
<li data-bind="text: companyTariff"></li>
</ul>
If you need to nest any other properties, you'll have to change it so the properties are actually observable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With