Search code examples
knockout.jsforeachko.observablearray

KnockoutJS observableArray with template and foreach


I'm trying to bind a Knockout observableArray to my UI using a foreach and checkboxes and then create an array based on what is checked.

I'm getting this error: Uncaught ReferenceError: Unable to process binding "template: function () . . . ."

Here is my HTML:

<dl data-bind="template: { name: 'QuarterTemplate', foreach: Quarter, templateOptions: { selections: SelectedQuarters } }"></dl>

<script id="QuarterTemplate" type="text/html">
<dd>
    <label>
        <input type="checkbox" data-bind="attr: { value: quarter }, checked: $item.selections" />
        <a data-bind="text: quarter" ></a>
    </label>
</dd>
</script>

Here is my Knockout ViewModel:

function ViewModel() {

this.Quarter = ko.observableArray([
    { quarter: "Q1" },
    { quarter: "Q2" },
    { quarter: "Q3" },
    { quarter: "Q4" }
]);

this.SelectedQuarters = ko.observableArray();

this.SelectedQuarters.subscribe(function () {
    console.log(this.SelectedQuarters());
});

}

$(document).ready(function () {

    ko.applyBindings(new ViewModel());

});

I also have a fiddle set up:

http://jsfiddle.net/SpRLP/1/

Ultimately what I want to see in the console is something like this:

Q1

Q1,Q3

Q1,Q3,Q2

Q1,Q3,Q2,Q4

Q1,Q2,Q4


Solution

  • templateOptions is only available when using the jQuery Templates plugin. When using KO native templating, it is most common to use $root or $parent to bind in this way. Here is some documentation on these context variables.

    So, it would look like:

    <dl data-bind="template: { name: 'QuarterTemplate', foreach: Quarter }"></dl>
    
    <script id="QuarterTemplate" type="text/html">
        <dd>
            <label>
                <input type="checkbox" data-bind="attr: { value: quarter }, checked: $parent.SelectedQuarters" />
                <a data-bind="text: quarter" ></a>
                </label>
    </dd>
    </script>
    

    Here is an updated fiddle: http://jsfiddle.net/rniemeyer/tY5TF/