knockout (only) example

by Shrikrishna Gupta

HTML

<ul data-bind="foreach: items">
    <li>
        <input type='checkbox' data-bind="checkedInArray: { array: $parent.itemsSel, value: $data }" /> <span data-bind="text:name"></span>  <a href="#" data-bind="click:$root.deselectOthers">only</a>
    </li>
</ul>
<hr/>
<ul data-bind="foreach: moreitems">
    <li>
        <input type='checkbox' data-bind="checkedInArray: { array: $parent.moreitemsSel, value: $data }" /> <span data-bind="text:name"></span>  <a href="#" data-bind="click:$root.moreDeselectOthers">only</a>
    </li>
</ul>

CSS

a {
    font-size:9px;
}

JavaScript

// ko.utils.addOrRemoveItem isn't exported
ko.utils.addOrRemoveItem = function(array, value, included) {
    var existingEntryIndex = array.indexOf ? array.indexOf(value) : utils.arrayIndexOf(array, value);
    if (existingEntryIndex < 0) {
        if (included)
            array.push(value);
    } else {
        if (!included)
            array.splice(existingEntryIndex, 1);
    }
};

ko.bindingHandlers.checkedInArray = {
    init: function (element, valueAccessor) {
        ko.utils.registerEventHandler(element, "click", function() {
            var options = ko.utils.unwrapObservable(valueAccessor()),
                array = options.array, // don't unwrap array because we want to update the observable array itself
                value = ko.utils.unwrapObservable(options.value),
                checked = element.checked;
            ko.utils.addOrRemoveItem(array, value, checked);
        });
    },
    update: function (element, valueAccessor) {
        var options = ko.utils.unwrapObservable(valueAccessor()),
            array = ko.utils.unwrapObservable(options.array),
            value = ko.utils.unwrapObservable(options.value);
        
        element.checked = ko.utils.arrayIndexOf(array, value) >= 0;
    }
};

var Item = function (name) {
    this.name = name;
};

var ViewModel = function () {
    var self = this;

    function getDeselectOthers(obsArr) {
        return function(me) {
            obsArr([me]);
        };
    };

    //first group
    self.items = ko.observableArray();
    self.items.push(new Item("one"));
    self.items.push(new Item("two"));
    self.items.push(new Item("three"));
    self.itemsSel = ko.observableArray(self.items.slice(0));
    self.deselectOthers = getDeselectOthers(self.itemsSel);

    //second group
    self.moreitems = ko.observableArray();
    self.moreitems.push(new Item("four"));
    self.moreitems.push(new Item("five"));
    self.moreitems.push(new Item("six"));
    self.moreitemsSel =...