0

The JSON returned from my server has optional attributes (e.g.) CompanyNumber is sometimes NULL and therefore it's removed from the JSON response for that specific company. (JMSSerializeBundle).

If I bind it to render all the companies in a table it crashes as soon as there's a company without a CompanyNumber. Is there way to prevent this from happening?

Current code:

<script type="text/javascript">
$(document).ready(function() {
    $.getJSON(Routing.generate('contacts_companies_get_json'), function(data) {
    var companies = ko.mapping.fromJS(data);
    ko.applyBindings({
        'companies': companies
    });
 })
});
</script>

   <table class="table">
   <thead>
       <tr>
           <th>Name</th>
           <th>Company Number</th>
           <th>Account</th>
           <th>Supplier</th>
           <th>Competitor</th>
           <th>Other</th>
           <th></th>
       </tr>
   </thead>
   <tbody data-bind="foreach: companies">
       <tr>
           <td><a href="#" class="title"><span data-bind="text: name"></span> <span data-bind="text: legal_form"></span></a></td>
           <td><span data-bind="text: company_number"></span></td>
           <td><span data-bind="if: type_account" ><i class="icon-check"></i></span></td>
           <td><span data-bind="if: type_supplier" ><i data-bind="if: type_supplier" class="icon-check"></i></span></td>
           <td><span data-bind="if: type_competitor" ><i data-bind="if: type_competitor" class="icon-check"></i></span></td>
           <td><span data-bind="if: type_other" ><i data-bind="if: type_other" class="icon-check"></i></span></td>
           <td><a class="btn btn-mini">Details</a><td>
       </tr>
   </tbody>
</table>
Simon
  • 1,643
  • 7
  • 30
  • 61
  • possible duplicate of [knockout viewmodel property undefined](http://stackoverflow.com/questions/9281196/knockout-viewmodel-property-undefined) – nemesv Apr 08 '13 at 19:24

1 Answers1

1

Can you try this:

<div data-bind="text: name() ? name() : ''"></div>

Reference: https://groups.google.com/forum/?fromgroups=#!topic/knockoutjs/fhVmPzRjdOs

Possible duplicate: knockout viewmodel property undefined

Community
  • 1
  • 1
lucuma
  • 18,247
  • 4
  • 66
  • 91
  • I'm getting this error Uncaught Error: Unable to parse bindings. Message: ReferenceError: company_number is not defined; Bindings value: text: company_number() ? company_number() : '' It works for the first one (which has a company number). The rendering stops when it hits the first company without a company number. (The company number is not defined in the JSON tree for that company when it's NULL) – Simon Apr 08 '13 at 19:19
  • 1
    I've added another link to a question that seems to be what you are looking for. – lucuma Apr 08 '13 at 19:21