I am having trouble binding to elements created by a Knockout template triggered by an AJAX call in the afterRender event. As you can see in this Fiddle the results render properly but in the afterRender event handler the elements still aren’t available.
Questions…
-
How is the template even rendering properly since it doesn’t appear to have rendered when the afterRender event handler runs?
-
Why does the AJAX call affect the outcome? If you uncomment out the line above the AJAX call, the template elements are available in the afterRender event.
Here is the code…
HTML
<div id="plugin" data-bind="template: { name: 'fooTemplate', data: $data, afterRender: postProcess }"></div>
<br />
<br />
<hr />
<div id="results"></div>
<script type="text/html" id="fooTemplate">
<div data-bind="foreach: items()">
<span data-bind="text: displayText"></span>
</div>
</script>
JAVASCRIPT
var data = {
items: [{
displayText: 'Name',
}, {
displayText: 'Last Login Date',
}, {
displayText: 'Email',
}]
};
function DataModel() {
var self = this;
self.items = ko.observableArray([]);
self.data = ko.dependentObservable(function () {
//self.items(data.items);// <<== UNCOMMENT THIS LINE AND THE postProcess FUNCTION SHOWS FULLY RENDERED DOM
$.ajax({
url: '/some/path',
error: function () {
self.items(data.items);
}
});
});
postProcess = function () {
$('#results').text($('#plugin').html());
}
}
dataModel = new DataModel();
ko.applyBindings(dataModel);
One note…the fiddle makes an AJAX call to a bogus address. This was so the Fiddle doesn’t have a server dependency. The error property is leveraged to change the data which causes the template to run. However, in my development environment calling a valid url yields the same outcome as displayed in the fiddle. Also, I am not using data returned from a server to load the template. Rather the fiddle uses a statically defined data source at the top (again just to demo the problem).
Looking at your example, you’re running into an async issue.
Here’s how the flow works without the $.ajax call:
But with the $.ajax call, the done (and error) methods are callbacks, so the flow changes:
I think the easiest fix is to pull your ajax call out of your dependentObservable to allow the situation you have commented out.