Reputation: 155
I have simple partial view in cshtml with simple view model, like this:
<script type="text/html" id="@WebSite.Models.DialogTemplates.NewUser">
<div id="change-state">
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>
</div>
</script>
<script type="text/javascript">
function AppViewModel() {
this.firstName = ko.observable("");
this.lastName = ko.observable("");
this.fullName = ko.computed(function()
{
return this.firstName() + " " + this.lastName();
}, this);
}
ko.applyBindings(new AppViewModel());
</script>
I show this partial view like popup dialog but I do not figure out how to call applyBindings. If I call this after define model, than applyBindings is call before create dialog and not work. I try this too. Can you call ko.applyBindings to bind a partial view?
ko.applyBindings(new AppViewModel(), document.getElementById("change-state"));
Upvotes: 0
Views: 3322
Reputation: 2313
Here is fiddle demostrating possible solution: http://jsfiddle.net/tabalinas/LhRuC/
You can create the dialog with { autoOpen: false } and show it when needed.
HTML:
<script type="text/html" id="tmpl">
<div id="change-state">
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>
</div>
</script>
<div id="popup">
<div data-bind="template: { name: 'tmpl' }"></div>
</div>
<button id="show">Show</button>
JS:
function AppViewModel() {
this.firstName = ko.observable("test");
this.lastName = ko.observable("test");
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new AppViewModel(), $("#popup").get(0));
$("#popup").dialog({
autoOpen: false
});
$("#show").click(function() {
$("#popup").dialog("open");
});
Not sure I completely got the problem you faced. If this won't work for you, provide more details in comments.
Upvotes: 3