1

我有一个对象列表,我循环并为它们创建单选按钮,然后我想将选择的对象存储在 observable 中,但我不知道该怎么做。这个小提琴是我试图做的事情的例子:jsfiddle.net/whx96806/,但它不起作用。

 <div data-bind="foreach: items">
<input type="radio" name="test" data-bind="checkedValue: $data, checked: $root.chosenItem" />
<span data-bind="text: itemName"></span>
</div>
<div><p>You have selected: <span data-bind="text:JSON.stringify(chosenItem())"></span></p></div>
<button data-bind="click:print">Print</button>

和js代码:

function ViewModel () {
    items= ko.observableArray([
    { itemName: 'Choice 1' },
    { itemName: 'Choice 2' }
    ]);
    chosenItem= ko.observable();

    print = function () { alert(chosenItem()); };

};

var vm = new ViewModel();
ko.applyBindings(vm);
4

2 回答 2

2

这是小提琴:http: //jsfiddle.net/whx96806/1/

请试试这个片段,看看它是否有帮助:

var ViewModel = {    
    items : ko.observableArray([
    { itemName: 'Choice 1' },
    { itemName: 'Choice 2' }
    ]),
    chosenItem : ko.observable(),

};

ko.applyBindings(ViewModel);
于 2015-11-01T22:04:56.917 回答
0

问题是我忘记在我的视图模型中使用“this”,这应该可以工作:

function ViewModel () {
    this.items= ko.observableArray([
    { itemName: 'Choice 1' },
    { itemName: 'Choice 2' }
    ]);
    this.chosenItem= ko.observable();

    print = function () { alert(chosenItem()); };

};

var vm = new ViewModel();
ko.applyBindings(vm);

这是小提琴:http: //jsfiddle.net/whx96806/2/

于 2015-11-02T12:40:26.970 回答