從我的服務器返回的JSON具有可選屬性(例如)CompanyNumber有時爲NULL,因此將其從特定公司的JSON響應中刪除。 (JMSSerializeBundle)。Knockout.js JSON數據具有可選屬性
如果我綁定它以呈現表中的所有公司,只要有公司沒有CompanyNumber,就會崩潰。有沒有辦法來防止這種情況發生?
當前代碼:
<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>
可能重複[淘汰賽視圖模型屬性未定義]( http://stackoverflow.com/questions/9281196/knockou t-viewmodel-property-undefined) – nemesv 2013-04-08 19:24:41