knockout 經過teplate實現簡單的代碼實現複雜的操做綁定checkbox,代碼以下自我感受很贊!!!html
前臺HTmlapp
<ul data-bind="template: { name: 'choiceTmpl', foreach: choices, templateOptions: { selections: selectedChoices } }">
</ul>
<script id="choiceTmpl" type="text/html">
< li > <input type = "checkbox"data - bind = "attr: { value: $data }, checked: $item.selections" / ><span data - bind = "text: $data" > </span> </li >
</script>
<hr />
<div data-bind="text: ko.toJSON(selectedChoices)">
</div>
<hr />
<div data-bind="text: selectedChoicesDelimited">
</div>this
前臺JSspa
var viewModel = { choices: ["one", "two", "three", "four", "five"], selectedChoices: ko.observableArray(["two", "four"]) };.net
viewModel.selectedChoicesDelimited = ko.dependentObservable(function() { return this.selectedChoices().join(","); }, viewModel);htm
ko.applyBindings(viewModel);three
在線Fiddle演示以下ip