Knockout js - && in if condition and containerless binding

Ashwin picture Ashwin · May 4, 2013 · Viewed 10.3k times · Source

I am displaying a list of items and if the items are not available I have to display a default message. Now, I have to check whether the object has been created and then check the object has the list in it.

So now, I am doing the below and it works it creates unnecessary dom elements. But, when I do the same with the containerless binding it doesn't seem to work and also is there an && syntax for if in KO

<span data-bind="if: object"> 
    <span data-bind="if: !object().property">
         <p> The list is not available </p>
    </span> 
</span> // Works 

<!-- ko if: object -->
     <!-- ko if: !object().property -->
          <p> The list is not available </p>
     <!-- /ko -->
<!-- /ko -->  // Doesn't work 

Thanks

Answer

Ricardo Medeiros Penna picture Ricardo Medeiros Penna · May 5, 2013

As mentioned by CodeThug, using the solutions you provided would display the message until ko.applyBindings have finished. A more verbose solution, but that would avoid the problem without relying on CSS, is to use dynamic templates as shown in the following jsfiddle:

http://jsfiddle.net/sAkb4/1/

This will create the valid markup inside the virtual element only when the ko.applyBindings is done.

<!-- ko template: { name: dinamycList } -->
<!-- /ko -->

<script type="text/html" id="empty-template">
  ... list is NOT available markup ...
</script>

<script type="text/html" id="list-template">
  ... list is available markup ...
</script>

Being dinamycList a function that returns the name of the template according to the verifications you want for a valid list.

EDIT:

Reading thru your last comment made me think if the behaviour that you want is to display the "not avaiable template" only after calculating the list and the property is false, if thats the case, the following fiddle will fix the last one to provide the right condition.

http://jsfiddle.net/sAkb4/3/

The "if" condition in template will handle the moment after knockout is ready, but before the list is. If the condition gets too messy, i would advise to put it inside a ko.computed for a clear markup.

<!-- ko template: { name: dinamycList, if: object() !== undefined && object().property !== undefined } -->
<!-- /ko -->