使用Knockout Data绑定在html页面上编写逻辑

时间:2015-05-25 10:40:59

标签: javascript jquery knockout.js

我是Knockout的新手,并使用已经实现的代码进行编辑。 我在html页面上写了一个逻辑,其中KO被绑定,但是没有工作。

data-bind='visible: ($data.isFellowTypeApplication && ($data.memberTypeId.toUpperCase() != "9F8CF4C5-F067-4A18-A1C0-A2F91CDD803A") && ($data.memberTypeId.toUpperCase() != "D8E6E36A-777F-4344-87FB-E8010C80A88E"))'

有人建议我做错了甚至KO允许在这里写逻辑吗?

            <div class="form-group fellow-publication" data-bind='visible: ($data.isFellowTypeApplication && ($data.memberTypeId.toUpperCase() != "9F8CF4C5-F067-4A18-A1C0-A2F91CDD803A") && ($data.memberTypeId.toUpperCase() != "D8E6E36A-777F-4344-87FB-E8010C80A88E"))'>
                <div class="controls cbCertify col-sm-12">
                    <input type="checkbox" id="Checkbox4" name="Checkbox2" data-bind='checked: $data.isLikeToMember' />
                    Should be visible only if above condition gets true.
                </div>
            </div>

2 个答案:

答案 0 :(得分:0)

您应该在javascript视图模型中创建一个ko.computed变量来控制此项目是否可见。类似的东西:

this.isVisible = ko.computed(function() {
        return isFellowTypeApplication && (memberTypeId.toUpperCase() != "9F8CF4C5-F067-4A18-A1C0-A2F91CDD803A") && (memberTypeId.toUpperCase() != "D8E6E36A-777F-4344-87FB-E8010C80A88E");
    }, this);

然后,您可以将HTML更新为:

<div class="form-group fellow-publication" data-bind='visible: $data.isVisible'>
  <div class="controls cbCertify col-sm-12">
    <input type="checkbox" id="Checkbox4" name="Checkbox2" data-bind='checked: $data.isLikeToMember' />
       Should be visible only if above condition gets true.
   </div>
</div>

这也使您更容易调试。

答案 1 :(得分:0)

@Kez答案也有效,但最后HTML上的逻辑也奏效了。这是我用过的代码。

            <div class="form-group fellow-publication" data-bind='visible: ($data.isFellowTypeApplication)'>
                <div class="controls cbCertify col-sm-12" data-bind='visible: $data.memberTypeId.toUpperCase() != "9F8CF4C5-F067-4A18-A1C0-A2F91CDD803A" && $data.memberTypeId.toUpperCase() != "D8E6E36A-777F-4344-87FB-E8010C80A88E"'>
                    <input type="checkbox" id="Checkbox4" name="Checkbox2" data-bind='checked: $data.isLikeToMember' />
                    Should be visible only if above condition gets true.
                </div>
            </div>