剔除条件绑定(但不是本机的“if”方式)

Knockout conditional binding (but not the native "if" way)

本文关键字:if 方式 本机 条件 绑定      更新时间:2023-09-26

我有一个案例看起来像这样(过于简化):

<!-- ko if: readOnly() -->
<a href="url" data-bind="click: ToggleReadOnly()" />
<!-- /ko -->
<!-- ko ifnot: readOnly() -->
<a href="url" data-bind="visible: someObservable" />
<!-- /ko -->

由于还有许多其他事情会使测试成倍增加,并重复大量代码,我需要能够在一行中完成这项工作,比如:

<a href="url" data-bind="if: readOnly() { click: ToggleReadOnly() } else: { visible: someObservable }"  />

有办法做到这一点吗?

有几种方法可以实现这一点。每个人都有自己的长处和短处。但我将专注于使用模板。

为每个状态创建一个模板,无论该状态是否以只读模式呈现。您只需要在模型中添加一个函数来决定使用哪个模板。

<script type="text/html" id="template-readonly-link">
    <a href="#" data-bind="click: ToggleReadOnly">ReadOnly</a>
</script>
<script type="text/html" id="template-readwrite-link">
    <a href="#" data-bind="visible: someObservable">ReadWrite</a>
</script>
<!-- ko template: { name: selectTemplate } --><!-- /ko -->
function ViewModel() {
    this.readOnly = ko.observable(true);
    this.someObservable = ko.observable(true);
    this.ToggleReadOnly = function (data, event) {
        this.readOnly(!this.readOnly());
        return false;
    }.bind(this);
    this.selectTemplate = function (data) {
        return this.readOnly()
            ? 'template-readonly-link'
            : 'template-readwrite-link';
    }.bind(this);
}

小提琴

您可以探索其他方法,如自定义组件、自定义绑定等。但这可能是最容易实现的。