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:
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.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:
You should look at the
with
binding, as well ascontrolsDescendantBindings
http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.htmlWhile 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: