撒拉嘿哟木头 2011-09-08 03:25 采纳率: 100%
浏览 332
已采纳

可以调用 ko.applyBindings 绑定部分视图吗?

I'm using KnockoutJS and have a main view and view model. I want a dialog (the jQuery UI one) to popup with another view which a separate child view model to be bound to.

The HTML for the dialog content is retrieved using AJAX so I want to be able to call ko.applyBindings once the request has completed, and I want to bind the child view model to just the portion of the HTML loaded via ajax inside the dialog div.

Is this actually possible or do I need to load ALL my views and view models when the page initially loads and then call ko.applyBindings once?

转载于:https://stackoverflow.com/questions/7342814/can-you-call-ko-applybindings-to-bind-a-partial-view

  • 写回答

4条回答 默认 最新

  • perhaps? 2011-09-08 03:38
    关注

    ko.applyBindings accepts a second parameter that is a DOM element to use as the root.

    This would let you do something like:

    <div id="one">
      <input data-bind="value: name" />
    </div>
    
    <div id="two">
      <input data-bind="value: name" />
    </div>
    
    <script type="text/javascript">
      var viewModelA = {
         name: ko.observable("Bob")
      };
    
      var viewModelB = {
         name: ko.observable("Ted")
      };
    
      ko.applyBindings(viewModelA, document.getElementById("one"));
      ko.applyBindings(viewModelB, document.getElementById("two"));
    </script>
    

    So, you can use this technique to bind a viewModel to the dynamic content that you load into your dialog. Overall, you just want to be careful not to call applyBindings multiple times on the same elements, as you will get multiple event handlers attached.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?