Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
MASTERING KNOCKOUTJS

You're reading from   MASTERING KNOCKOUTJS Use and extend Knockout to deliver feature-rich, modern web applications

Arrow left icon
Product type Paperback
Published in Nov 2014
Publisher
ISBN-13 9781783981007
Length 270 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
Timothy Moran Timothy Moran
Author Profile Icon Timothy Moran
Timothy Moran
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Knockout Essentials 2. Extending Knockout with Custom Binding Handlers FREE CHAPTER 3. Extending Knockout with Preprocessors and Providers 4. Application Development with Components and Modules 5. Durandal – the Knockout Framework 6. Advanced Durandal 7. Best Practices 8. Plugins and Other Knockout Libraries 9. Under the Hood Index

Containerless control flow

So far, we have looked at using the control flow bindings (if, with, foreach, and template) and the standard data-bind attribute on an HTML element. It is also possible to use control flow bindings without an element by using special comment tags that are parsed by Knockout. This is called containerless control flow.

Adding a <!— ko --> comment starts a virtual element that ends with a <!-- /ko --> comment. This virtual element causes a control flow binding to treat all contained elements as children. The following block of code demonstrates how sibling elements can be grouped by a virtual comment container:

<ul>
    <li>People</li>
    <li>Locations</li>
    <!-- ko if: isAdmin -->
    <li>Users</li>
    <li>Admin</li>
    <!-- /ko -->
</ul>

List elements only allow specific elements as children. The preceding containerless syntax applies the if binding to the last two elements in the list, which causes them to add or remove from the DOM based in the isAdmin property:

<ul>
    <li>Nav Header</li>
    <!-- ko foreach: navigationItems -->
    <li><span data-bind="text: $data"></span></li>
    <!-- /ko -->
</ul>

The preceding containerless syntax allows us to have a foreach binding to create a list of items while maintaining a header item at the top of the list.

All of the control flow bindings can be used in this way. The preceding two examples can be seen in the cp1-containerless branch.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at R$50/month. Cancel anytime