你可以调用 ko.applyBindings 来绑定局部视图吗? [英] Can you call ko.applyBindings to bind a partial view?

查看:21
本文介绍了你可以调用 ko.applyBindings 来绑定局部视图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 KnockoutJS 并且有一个主视图和视图模型.我想要一个对话框(jQuery UI 的一个)弹出另一个视图,一个单独的子视图模型要绑定到.

对话框内容的 HTML 是使用 AJAX 检索的,因此我希望能够在请求完成后调用 ko.applyBindings,并且我想将子视图模型绑定到该部分在对话框 div 中通过 ajax 加载的 HTML.

这真的可能吗,还是我需要在页面最初加载时加载所有视图和视图模型,然后调用 ko.applyBindings 一次?

解决方案

ko.applyBindings 接受第二个参数,该参数是用作根的 DOM 元素.

这会让你做类似的事情:

<input data-bind="value: name"/>

<div id="两个"><input data-bind="value: name"/>

<script type="text/javascript">var viewModelA = {名称:ko.observable("Bob")};var viewModelB = {名称:ko.observable("Ted")};ko.applyBindings(viewModelA, document.getElementById("one"));ko.applyBindings(viewModelB, document.getElementById("two"));

因此,您可以使用此技术将 viewModel 绑定到加载到对话框中的动态内容.总的来说,您只是要小心不要在同一元素上多次调用 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?

解决方案

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.

这篇关于你可以调用 ko.applyBindings 来绑定局部视图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆