ID separation

by ZenMaster

HTML

<script src="http://knockoutjs.com/downloads/knockout-3.0.0rc.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.3.5/knockout.mapping.js"></script>
<ul id="group1" data-bind="foreach: group.items">
    <li>
        <input type="radio" data-bind="attr: {id: id, name: $root.group.name}">
        <label data-bind="attr: {for: id}, text: name"></label>
    </li>
</ul>
<hr>
<ul id="group2" data-bind="foreach: group.items">
    <li>
        <input type="radio" data-bind="attr: {id: id, name: $root.group.name}">
        <label data-bind="attr: {for: id}, text: name"></label>
    </li>
</ul>

CSS

div {
    height: 50px;
    width: 200px;
    background: #ccc;
    border: 1px solid #aaa;
}

div.is-active {
    background: #f00;
}

ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

JavaScript

var _active = function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
    var value = KO.unwrap(valueAccessor());

    if(value === viewModel.id()) {
        $(element).addClass('is-active');
    } else {
        $(element).removeClass('is-active');                
    }
};

KO.bindingHandlers.isActive = {
    init: _active,
    update: _active
};

var observable = ko.mapping.fromJS({                
    group1: {
        name: 'group1',
        items: [
            {id: 'i1', name: 'Item 1'},
            {id: 'i2', name: 'Item 2'},
            {id: 'i3', name: 'Item 3'}
        ]
    },
    group2: {
        name: 'group2',
        items: [
            {id: 'i1', name: 'Item 11'},
            {id: 'i2', name: 'Item 22'},
            {id: 'i3', name: 'Item 33'}
        ]
    }
}, {
    group1: {
        items: {            
            key: function(data) {
                return ko.unwrap(data.id);
            }
        }
    },
    group2: {
        items: {            
            key: function(data) {
                return ko.unwrap(data.id);
            }
        }
    }
});

// Swap the following lines to apply different data sets.
ko.applyBindings({group: observable.group1}, document.getElementById('group1'));
ko.applyBindings({group: observable.group2}, document.getElementById('group2'));