I noticed a strange behavior in Knockout’s template rendering.
I have a simple Knockout example…
var viewModel = {
stuff : ko.observable([{ id : 1, name : 'Thing'},
{ id: 2, name : 'Thingier' },
{ id : 3, name : 'Thingiest' }]),
render: function(el){
console.log(el);
}
}
$(function(){
ko.applyBindings(viewModel);
});
And the Html…
<ul data-bind="template: { name: 'thingTemplate',
foreach: stuff,
afterRender: render }">
</ul>
<!--
<script id="thingTemplate" type="text/html">
<li>
<span data-bind="text: name"></span>
</li>
</script>-->
<script id="thingTemplate" type="text/html">
<span data-bind="text: name"></span>
</script>
When the render function is called when using the template which is currently commented out, I get a console.log of jQuery(li).
When the reunder function is called with the current template I get console.log of jQuery(Comment { length=0, nodeName=”#comment”, nodeType=8, more…}, span).
What’s with that comment node?
Here’s the working fiddle… http://jsfiddle.net/jcreamer898/fqrv7/
According to the KnockoutJS documentation, the afterRender callback will be invoked, passing “an array of DOM nodes just rendered by the template.” In other words, your render callback should be expecting an array of nodes.
Now, your question is why are you seeing a comment element coming back. My question is, do you see that same comment element even if you remove your <li> block?