Book Image

Mastering KnockoutJS

By : Timothy Moran
Book Image

Mastering KnockoutJS

By: Timothy Moran

Overview of this book

Table of Contents (16 chapters)
Mastering KnockoutJS
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Templates


Knockout's template system is incredibly flexible: it works with anonymous templates, named templates, and allows the engine that renders templates to be overridden. The template binding is also used by the foreach binding, which is just a syntactic sugar for the { foreach: someExpression } template. To understand how the template system works, let's start with the template-binding handler.

The template binding handler

The init function of the template binding understands that templates can either be named (loaded from a source) or inline (loaded using the contents of the bound element):

'init': function(element, valueAccessor) {
  // Support anonymous templates
  var bindingValue = ko.utils.unwrapObservable(valueAccessor());
  if (typeof bindingValue == "string" || bindingValue['name']) {
    // It's a named template - clear the element
    ko.virtualElements.emptyNode(element);
  } else {
    var templateNodes = ko.virtualElements.childNodes(element),
    container = ko.utils.moveCleanedNodesToContainerElement...