0
请参阅here。Knockout如何将对象绑定到复选框和收音机
如何将一个对象(不可观察)绑定到一个复选框和广播值,以便我得到的值(值和值)是一个普通对象(无可观察)。
HTML:
Selection List
<a class="pull-right" href="#" data-bind="click: addChoice">+</a>
<table class="selection" data-bind="foreach: Choices">
<tr>
<td><input type="text" data-bind="value: Id" /></td>
<td><input type="text" data-bind="value: Text" /></td>
</tr>
</table>
Checkbox Values: <br />
<!-- ko foreach: {data: Choices() } -->
<input type="checkbox" data-bind="value: ko.toJS($data), checked: $root.Values" /><span data-bind="text: Text" ></span><br />
<!-- /ko -->
Radio Value: <br />
<!-- ko foreach: {data: Choices() } -->
<input type="radio" data-bind="value: ko.toJS($data), checked: $root.Value" /><span data-bind="text: Text" ></span><br />
<!-- /ko -->
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
的Javascript:
function VM() {
var self = this
self.Value = ko.observable()
self.Values = ko.observableArray([])
self.Choices = ko.observableArray([])
self.Choice = function (id, text) {
this.Id = ko.observable(id)
this.Text = ko.observable(text)
}
self.addChoice = function() { self.Choices.push(new self.Choice("C" + (self.Choices().length + 1), "Text Here")) }
}
var vm = new VM()
ko.applyBindings(vm)