Knockout:无需扩展模型即可选择表行?

2024-01-23

我有通过淘汰赛呈现的下表模板:

            <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>

现在我想让行可单击,并希望在选择行时分配一个 css 类。 一次只能选择 1 (!) 行,因此必须取消选中其他行。

最简单的方法是使用选定的属性扩展我的模型(产品类),但这会破坏我与服务器端的 1:1 映射。

我应该如何解决这个问题? 你会如何处理这个问题?


这是我现在的最终解决方案,没有额外的隐藏单选按钮:

<tr data-bind="click: $root.selectProduct, css: { 'active-row': $root.selectedProduct() === $data }">

以及 ViewModel 中的 selectedProduct 实现:

function AppViewModel() {
    // Private
    var self = this;

    // Public Properties
    self.selectedProduct = ko.observable();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Knockout:无需扩展模型即可选择表行? 的相关文章