Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout JS: checking for the existence of an observable in an IF binding

Tags:

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?

like image 698
Jack Avatar asked Feb 24 '12 07:02

Jack


People also ask

What is Ko observable in KnockoutJS?

Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.

What is two-way data binding in KnockoutJS?

KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.


2 Answers

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

like image 175
Oybek Avatar answered Sep 19 '22 15:09

Oybek


<!-- ko if: typeof specialText != 'undefined' -->

Based on Oybek's solution, you could also do:

<!-- ko foreach: Items -->
    <strong data-bind="text: Foo"></strong>
    <br />
    <!-- ko if: "Bar" in $data -->
        <p data-bind="text: Bar"></p>
    <!-- /ko -->
<!-- /ko -->​

Example: http://jsfiddle.net/MecNx/56/

like image 37
paulslater19 Avatar answered Sep 19 '22 15:09

paulslater19