【问题标题】:Is there a way to pass binding context to 'if' binding in knockout?有没有办法在淘汰赛中将绑定上下文传递给“if”绑定?
【发布时间】:2013-07-29 14:13:14
【问题描述】:

这是我必须使用的一个小 jsfiddle 示例:http://jsfiddle.net/SHjXg/3/

由于淘汰赛不允许我将 'with' 和 'if' 绑定绑定到单个元素,因此我目前使用 2 个嵌套 div 而不是一个来完成此操作。

<div class="item" data-bind="with:items.item1">
    <div data-bind="if:ready()">
        <!-- content here is different for each item and depends on item 
             properties which are not available before ready() is set to true. -->
    </div>
</div>

我能否以某种方式将绑定上下文与现有的“if”绑定一起传递给每个项目只使用一个 div,还是应该为此创建一个自定义绑定?

【问题讨论】:

    标签: javascript data-binding knockout.js


    【解决方案1】:

    你可以使用如下语法:

    &lt;div class="item" data-bind="template: { data: items.item1, 'if': items.item1.ready }"&gt;

    此语法与with 的当前版本之间只有细微差别,因为它不会保留原始元素。

    否则,您可以选择使用无容器绑定,例如:

    &lt;!-- ko if: ready --&gt;content&lt;!-- /ko --&gt;

    【讨论】:

    • 我正在考虑使用模板,但项目中唯一重复出现的部分是容器 div 本身,因此我也想保留原始元素。我不得不猜测上下文不能沿着 if 绑定更改。与使用自定义绑定相比,添加无容器会导致更少的开销吗?
    • 如果您使用template 而不使用name,那么它使用子代作为“模板”。每当数据发生变化时,它都需要一个元素的副本来重用。我认为这可能是您最简单的选择。添加无容器if 绑定不会增加太多额外开销。我关于保留原始元素的评论只是为了澄清with 和以这种方式指定的template 绑定之间的细微差别。
    【解决方案2】:

    如果我没听错的话,你可以使用virtual element

    <div class="item" data-bind="with:items.item1">
        <!-- if : ready() -->       
            <!-- content here is different for each item and depends on item 
                 properties which are not available before ready() is set to true. -->
         <!-- /ko -->
    </div>
    

    【讨论】:

    • 是的,这确实摆脱了额外的 div,但使用虚拟元素会比自定义绑定导致更多开销吗?假设我的页面上碰巧有一百个这样的项目,它仍然调用 2 个活页夹..
    【解决方案3】:

    您可以使用非常有用的淘汰赛 cmets。

    http://knockoutjs.com/documentation/if-binding.html

    <ul>
        <li>This item always appears</li>
        <!-- ko if: someExpressionGoesHere -->
            <li>I want to make this item present/absent dynamically</li>
        <!-- /ko -->
    </ul>
    

    【讨论】:

      猜你喜欢
      • 2017-05-11
      • 1970-01-01
      • 2013-12-11
      • 2013-02-04
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      相关资源
      最近更新 更多