Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout js - check if property exists

Tags:

knockout.js

I am trying to render the following with knockout.

<!-- ko with: address-->
<!-- ko if: address1-->
<span style="display : block">
<span data-bind="varchar : address1"></span>
</span>
<span style="display : block">
<span data-bind="varchar : address2"></span>
</span>
<!-- /ko -->
<!-- /ko -->

The problem is that even if the address object is present it may not contain the address1 parameter. I'd like knockout to not render the nested spans if the parameter 'address1' is null. Currently the following error is thrown:

Unable to parse bindings. Message: ReferenceError: address1 is not defined;

Any help much appreciated.

like image 762
Chin Avatar asked Feb 28 '12 04:02

Chin


3 Answers

If you use <!-- ko if: $data.address1 -->, then it will not error out if address1 is undefined.

If address1 does later become populated, it will not update the UI though (address1 would need to be an observable originally).

like image 61
RP Niemeyer Avatar answered Nov 18 '22 16:11

RP Niemeyer


Isn't it just a case of moving your second if?

<!-- ko with: address -->
<span style="display : block">
<!-- ko if: address1 -->
<span data-bind="varchar : address1"></span>
<!-- /ko -->
</span>
<span style="display : block">
<span data-bind="varchar : address2"></span>
</span>
<!-- /ko -->

Looks like we need to see your viewModel and how addresses relate to each other. I can do that on the sample from knockout page with no problems:

<h1 data-bind="text: city"> </h1>
<p data-bind="with: coords">
    <!-- ko if: latitude -->
    Latitude: <span data-bind="text: latitude"> </span>,
    <!-- /ko -->
    Longitude: <span data-bind="text: longitude"> </span>
</p>
like image 23
veblock Avatar answered Nov 18 '22 17:11

veblock


I had a case where I had an address template being called from different places.

My 'country name' data field was sometimes countryName and sometimes countryDesc.

I just changed the template to this:

 <div data-bind="text: $data.countryName || $data.countryDesc"></div>

This takes advantage of the fact that if you use $data it won't error out (as pointed out by RP Niemeyer)

like image 6
Simon_Weaver Avatar answered Nov 18 '22 15:11

Simon_Weaver