繁体   English   中英

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

[英]Knockout conditional binding (but not the native “if” way)

我有一个这样的情况(过度简化):

<!-- 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);
}

小提琴

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM