我有通过knockout呈现的以下表格模板:
<table class="gv" data-bind="visible: products().length > 0">
<thead>
<th>Type</th>
<th>Name</th>
</thead>
<tbody data-bind="foreach: products">
<tr data-bind="click: $root.selectProduct">
<td data-bind="text: type"></td>
<td data-bind="text: name"></td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
现在我想使行可单击,并且如果选择了行,则想要分配一个css类.一次只能选择1(!)行,因此必须取消选中其他行.
最简单的方法是使用选定的属性扩展我的模型(产品类),但这会破坏我与服务器端的1:1映射.
我该如何解决这个问题?你会怎么处理这个?
tim*_*use 16
这是我现在的最终解决方案,没有额外隐藏的单选按钮:
<tr data-bind="click: $root.selectProduct, css: { 'active-row': $root.selectedProduct() === $data }">
Run Code Online (Sandbox Code Playgroud)
以及ViewModel中的selectedProduct实现:
function AppViewModel() {
// Private
var self = this;
// Public Properties
self.selectedProduct = ko.observable();
Run Code Online (Sandbox Code Playgroud)