Chen Kinnrot
Chen Kinnrot

Reputation: 21025

Knockout js working with the foreach control flow and radion as template

The 'checked' binding is not very compatible for radio button that generated by a foreach control flow.

example:

 <div data-bind="foreach: targetAudience">
        <div>
            <label>
                <input name="targetAudience" type="radio"  data-bind="checked:    isSelected,value:id" />
                <span data-bind="text: name"></span>
            </label>
        </div>
    </div>

each vm(single target) will get the id of the selected radio at the isSelected property. This looks a little smelly, is there a better way to know who is the selected radio?

Upvotes: 1

Views: 3025

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

The 'checked' binding when working with radio buttons is designed to populate the model with the "value" of the individual radio button rather than update a flag on each item in an array.

An easy way to make this work though is to have it populate a value on the parent and then add a computed observable on each item to determine whether its selected flag should be true or false.

Here is a sample:

var Item = function(id, name, selected) {
   this.id = id;
   this.name = ko.observable(name);
   this.selected = ko.computed(function() {
        return parseInt(selected(), 10) == this.id;  
   }, this);
};

var ViewModel = function() {
    this.selected = ko.observable(2);
    this.items = ko.observableArray([
        new Item(1, "one", this.selected),
        new Item(2, "two", this.selected),
        new Item(3, "three", this.selected)
       ]);
};

Then, bind like:

<ul data-bind="foreach: items">
    <li>
        <input type="radio" name="items" data-bind="attr: { value: id }, checked: $root.selected" />
        <span data-bind="text: name"></span>
    </li>
</ul>

http://jsfiddle.net/rniemeyer/zNkhR/

Upvotes: 3

Related Questions