Knockout Checkbox Binding

by codesailor

HTML

Available Items:
<div data-bind="foreach: $root.availableItems">
    <input type="checkbox" data-bind="value: id(), checked: $root.associatedItemIds, click: $root.toggleAssociation" />	
    <span data-bind="text: '&nbsp;' + Name()"></span>
    <br/>
</div>
<br/>
Associated Item Ids:
<div data-bind="foreach: $root.associatedItemIds">
    <span data-bind="text: $data"></span>
    <br/>
</div>

JavaScript

function DemoItem(id, name) {
    var self = this;

    self.id = ko.observable(id);
    self.Name = ko.observable(name);
    self.Selected = ko.observable(false);
}

function ViewModel() {
    var self = this;

    self.availableItems = ko.observableArray();
    self.associatedItemIds = ko.observableArray();

    self.init = function () {
        self.availableItems.push(new DemoItem(1, 'One'));
        self.availableItems.push(new DemoItem(2, 'Two'));
        self.availableItems.push(new DemoItem(3, 'Three'));
        self.availableItems.push(new DemoItem(4, 'Four'));
        self.availableItems.push(new DemoItem(5, 'Five'));
    };
    
    self.toggleAssociation = function (item) {
        if (item.Selected() === true) console.log("dissociate item " + item.id());
        else console.log("associate item " + item.id());
        item.Selected(!(item.Selected()));
        return true;
    };
}

var viewModel = new ViewModel();
ko.applyBindings(viewModel);
viewModel.init();