Knockoutjs After Render 渲染 Html 注释
我注意到 Knockout 的模板渲染中有一个奇怪的行为。
我有一个简单的 Knockout 示例...
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);
});
和 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>
当使用当前注释掉的模板时调用渲染函数时,我得到 jQuery(li) 的 console.log。
当使用当前模板调用 reunder 函数时,我得到 jQuery(Comment { length=0, nodeName="#comment", nodeType=8, more...}, span) 的 console.log 。
那个评论节点是怎么回事?
这是工作小提琴... http://jsfiddle.net/jcreamer898/fqrv7/
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/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我遇到了同样的问题,请参阅:
KnockoutJS 模板“beforeRemove”调用了 3 次而不是 1 次
我的解决方案如下(我知道不太好......):
I had the same problem, see:
KnockoutJS template 'beforeRemove' called three times instead of 1
My solution was the following (not great, I know..):
根据 KnockoutJS 文档,将调用 afterRender 回调,传递“一个 DOM 数组”刚刚由模板渲染的节点。”换句话说,您的渲染回调应该需要一个节点数组。
现在,您的问题是为什么会看到评论元素回来。我的问题是,即使您删除了
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?