【问题标题】:Exclude DOM elements from knockout apply binding?从淘汰赛应用绑定中排除 DOM 元素?
【发布时间】:2013-03-02 00:15:55
【问题描述】:

我想将我的淘汰视图模型定位到 dom 的某些部分,如下所示:

ko.applyBindings(MyViewModel,$('#Target')[0]);

但是我不希望它适用于它下面的所有 dom。这样做的原因是整个 SPA 的东西运行得不是很好 - 无法跟上将每个潜在交互包含到一个巨大对象中的巨型视图模型。因此,页面由多个局部视图组成。我希望每个部分都实例化自己的 ViewModel 并提供接口供父级交互。

一些示例 dom

<div id="Target">
     <!--Everything here should be included except-->
     <div data-bind="DoNotBindBelowThis:true">
          <!--Everything here should NOT be included by the first binding, 
              I will specifically fill in the binding with targetted
              ApplyBind eg. ko.applyBindings(MyOtherViewModel, $('#MyOtherTarget')[0])
              to fill the gaps-->
            <div id="MyOtherTarget">
            </div>
     </div>
</div>

再次,如何从applyBindings 中排除标有DoNotBindBelowThis 的div 下面的整个dom 树?

【问题讨论】:

    标签: javascript asp.net-mvc dom asp.net-mvc-4 knockout.js


    【解决方案1】:

    在此处查看博文:http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html

    基本上,您可以创建自定义绑定,例如:

    ko.bindingHandlers.DoNotBindBelowThis = {
        init: function() {
            return { controlsDescendantBindings: true };
        }
    };
    

    【讨论】:

    • 我不太明白,我们不应该返回 controlsDescendantBindings false,而不是 true?
    • controlsDescendantBindings: true 告诉 KO 我们(此绑定)将处理将绑定应用于我们的孩子。在上面的示例绑定中,已经完成了所有工作,因此孩子们被单独留下。然后,您可以返回并调用 ko.applyBindings 到特定 DOM 元素,该元素位于具有此绑定的元素内部。
    • 是的,做到了。谢谢。
    • RP - 前几天我偶然发现了你的博客文章,这真的很有帮助。我编写了一个自定义绑定来呈现 Backbone 样式的视图:gist.github.com/johntron/8047929
    猜你喜欢
    • 1970-01-01
    • 2014-05-31
    • 2013-07-02
    • 2013-01-18
    • 2017-05-05
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多