Search code examples
knockout.jsjquery-templates

Knockout databound templates


For some reason knockout requires jquery tmpl when you use databound templates, otherwise it will complain that it does not find the members (The databound data for the template is not yet set).

The tmpl engine does not support foreach bindings in a template

1) Is it a bug knockout, external engines should not be needed?

2) Is there a workaround using tmpl and foreach bindnigs in templates?

Fiddle (See error log) http://jsfiddle.net/C9kDL/

Thanks

edti: A example without foreach that works to show why how databound templates work http://jsfiddle.net/jvLyf/


Solution

  • Assuming you are not wedded to the tmpl library, you can get this working without the tmpl library (which as I'm sure you are aware is no longer being developed). If you just use native knockout templates you get the error:

    Uncaught Error: Unable to parse bindings. Message: TypeError: Cannot read property 'children' of undefined; Bindings value: foreach: children

    The reason for this is that selected starts out as null. Therefore, if we add a condition to the template call:

    <div data-bind="template: { name: 'test', data: selected, if: selected }"></div>
    

    .. then things work fine.

    See http://jsfiddle.net/unklefolk/Nrrv5/1/ for an example.

    Hope this is what you were looking for.