Knockout.js是一个很棒的库来实现MVVM。
以下最小样本使用knockout.js
绑定网格。
查看
<div id="divDecision">
<div id="divDecisionBinding" data-bind="template: { name: 'tmplDecision' }">/div>
<script id="tmplDecision" type="text/x-jquery-tmpl">
<table id="tblDecision">
<thead>
<tr>
<th>Candidate</th>
<th>Decision</th>
</tr>
</thead>
<tbody data-bind="foreach:decisionList" id="tbList">
<tr>
<td data-bind="text: candidate"></td>
<td>
<select data-bind="attr: { id: 'cmbDecision' + ':' + $index(), name: 'cmbDecision' + ':' + $index()}, options: viewModelDecision.decisionLookup, value: 'decision', optionsText: 'decision_desc', optionsCaption: 'Please select'"></select>
</td>
</tr>
</tbody>
</table>
</script>
</div>
viewModelDecision (2名成员:decisionLookup和decisionList)
decisionLookup
0 : {decision: "N", decision_desc: "No need"}
1 : {decision: "A", decision_desc: "Approved"}
2 : {decision: "R", decision_desc: "Rejected"}
decisionList
0 : {candidate: "000000001", decision: "A" }
1 : {candidate: "000000002", decision: "N" }
脚本
var viewModelDecision;
//viewModelDecision gets loaded from a web service
viewModelDecision = result;
//Now the binding happens
ko.applyBindings(viewModelDecision, document.getElementById("divDecision"));
输出
000000001 Please select
000000002 Please select
首饰
candidate
已成功绑定cmbDecision:X
的选项已成功绑定cmbDecision:X
的值不受约束 -
标题“Please select
”默认选中。问题
为什么默认情况下没有选择下拉列表的值?
答案 0 :(得分:1)
value
绑定应定位到您的viewmodel的可观察属性。
您可能打算使用optionsValue
绑定告诉knockout使用.decision
中存储的ID作为选择。
<select data-bind="options: viewModelDecision.decisionLookup, value: selectedDecision, optionsValue: 'decision', optionsText: 'decision_desc', optionsCaption: 'Please select'"></select>
在您的虚拟媒体中:
this.selectedDecision = ko.observable("A"); // Pre-select the 2nd item