Imagitron
Imagitron

Reputation: 25

knockout.js two-way binding of checkboxes with observableArrays

I'm new to knockout, and I'm having some trouble getting the checkbox to do what I want. First of all, here's the fiddle for what I've tried so far: http://jsfiddle.net/imagitron/mMc6k/, and the offending lines of code:

<input type="checkbox" data-bind="checked: $root.selectedItems"/>

Essentially, what I'm trying to do is link two arrays via the checkbox, so that when I click the checkbox, it stores the object from the definition array and saves it to the selectedItems array. Also the removeItems function isn't clearing the array when I press the button.

Thanks in advanced!

Upvotes: 2

Views: 652

Answers (1)

chiccodoro
chiccodoro

Reputation: 14716

As far as I know this is not supported out of the box by knockout. The checked binding binds the state of a single checkbox to a single boolean property. However for this to work in two ways, you need to indicate the function name instead of a function call ($root.someProperty instead of $root.someProperty()).

The value binding does not make sense for checkboxes. It is used to bind the value of other input fields such as text boxes.

To achieve what you want you could define an array with an object for each checkbox like so:

var items = ko.mapping.fromJS([
    { label: 'Foo', checked: false },
    { label: 'Bar', checked: false }
]);

And bind to it like so:

<!-- ko foreach: items -->

    <input type="checkbox" data-bind="checked: checked"/>
    <span data-bind="text: label"/>

<!-- /ko -->

Then retrieve the checked values of the array using a ko.computed function:

var checkedItems = ko.computed(function() {
    return _.filter(items, function (item) { return item.checked() });
});

(this is a hidden ad for the underscore library - if you don't have it, knockout has a similar function as far as I can remember)

Upvotes: 3

Related Questions