Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  178] [ 6]  / answers: 1 / hits: 24258  / 13 Years ago, fri, february 24, 2012, 12:00:00

I'm rendering a similar block of HTML for several slightly different objects. They're 90% the same, but each one has some specific quirks that demand extra observables. I would like to render each of these mostly-similar items in a template block, but I'm running into problems with undefined objects.



Basically, I want to check for the existence of an observable object before rendering it in the template.



I am trying to do something like this:



<div data-bind=foreach: blocks>
<h2 data-bind=text: normalHeader><h2>
<p data-bind=text: normalText></p>
<!-- ko if: specialText --><p data-bind=text: specialText></p><!-- /ko -->
</div>


So if specialText doesn't exist (not just has no value, but doesn't exist at all) for that iteration of blocks, ignore the conditional. The error I'm getting is:



Uncaught Error: Unable to parse bindings.
Message: ReferenceError: specialText is not defined;


From what I understand of Knockout's if binding, it should work if the object returns any kind of false-like value, like null or undefined, which means that the if binding should gracefully fail, which it definitely isn't.



Is there any way to make this work?


More From » knockout.js

 Answers
30

You might use the following approach:



<!-- ko foreach: Items -->
<strong data-bind=text: Foo></strong>
<br />
<!-- ko if: $data.hasOwnProperty(Bar) -->
<p data-bind=text: Bar></p>
<!-- /ko -->
<!-- /ko -->​


I've posted a working demo


[#87238] Thursday, February 23, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cherish

Total Points: 734
Total Questions: 94
Total Answers: 86

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;