可以调用 ko.applyBindings 来绑定部分视图吗?
我正在使用 KnockoutJS 并有一个主视图和视图模型。我想要弹出一个对话框(jQuery UI 对话框),其中包含另一个视图,该视图要绑定到一个单独的子视图模型。
对话框内容的 HTML 是使用 AJAX 检索的,因此我希望能够在请求完成后调用 ko.applyBindings,并且我希望将子视图模型仅绑定到 HTML 部分通过 ajax 在对话框 div 内加载。
这实际上可能吗?还是我需要在页面最初加载时加载所有视图和视图模型,然后调用 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
ko.applyBindings 接受第二个参数,该参数是用作根的 DOM 元素。
这将使您可以执行以下操作:
因此,您可以使用此技术将 viewModel 绑定到加载到对话框中的动态内容。总的来说,您只是要小心,不要对同一元素多次调用
applyBindings
,因为您将附加多个事件处理程序。ko.applyBindings
accepts a second parameter that is a DOM element to use as the root.This would let you do something like:
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.虽然 Niemeyer 的答案是对该问题的更正确答案,但您还可以执行以下操作:
这意味着您不必指定 DOM 元素,甚至可以将多个模型绑定到同一元素, 像这样:
While Niemeyer's answer is a more correct answer to the question, you could also do the following:
This means you don't have to specify the DOM element, and you can even bind multiple models to the same element, like this:
我已成功在运行时将自定义模型绑定到元素。 在这里: http://jsfiddle.net/ZiglioNZ/tzD4T/457/
代码 有趣的是,我将 data-bind 属性应用于我未定义的元素:
I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/
The interesting bit is that I apply the data-bind attribute to an element I didn't define:
您应该查看
with
绑定以及controlsDescendantBindings
http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.htmlYou should look at the
with
binding, as well ascontrolsDescendantBindings
http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.html