Reputation: 25
I'm sure I'm fundamentally misunderstanding something here but can't for the life of me work it out.
I'm using a jquery ui dialog to create a form popup. The view for the form is in a separate file so on opening the dialog I'm using Jquery.load() to populate the dialog.
I then want to apply knockout bindings.
I've recreated my problem with some simple code.
Main html file:
<script src="knockout-3.4.0.js"></script>
<script src="Jquery/jquery-1.12.2.js"></script>
<script src="jquery-ui-1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="jquery-ui-1.11.4/jquery-ui.css"">
<script>
$(document).ready(function(){
//initialise the dialog
$( "#dialog" ).dialog({
modal: true,
autoOpen: false
});
$("#btn").click(function(){
//open the dialog and load the html from the Popup page
$("#dialog").load('Popup.html').dialog("open");
//apply a simple binding to the container div in the Popup page
ko.applyBindings( {someText: "value from knockout"}, $("#container")[0] );
});
});
</script>
<button id="btn">Click</button>
<div id="dialog" style = "display: none;">the hidden Div</div>
The Popup html file:
<div id="container">
<p data-bind="text: someText">Default text in html popup</p>
</div>
If I replace
ko.applyBindings( {someText: "value from knockout"}, $("#container")[0] );
with
setTimeout(function(){
ko.applyBindings( {someText: "value from knockout"}, $("#container")[0] );
},200);
Then it works file (albeit with a small delay as expected) but that doesn't feel like the 'right' answer. That led me to believe that the applyBindings is running too quickly so I've tried placing in the callback of $.load() but I get the same result.
Am I missing something really obvious?
Upvotes: 2
Views: 945
Reputation: 49095
You need to make sure ko.applyBindings()
is being called after the contents of Popup.html
have been loaded (since Ajax is asynchronous and will not wait for the contents to be loaded before proceeding to the applyBindings()
call).
The easiest way to do it is to provide a callback function:
$("#dialog").load('Popup.html', function() {
$(this).dialog("open");
ko.applyBindings({someText: "value from knockout"}, $("#container")[0]);
})
See load()
Upvotes: 1