模板渲染后的KnockoutJS绑定事件 [英] KnockoutJS bind event after template render
问题描述
我已经搜索了一段时间,我非常有信心这是一个新问题,而不是标题所暗示的重复. :)
I've been searching for a while, and I'm pretty confident this is a new question, and not a repeat like the title suggests. :)
基本上,我正在尝试确定在使用jQuery模板之类的模板渲染后,KnockoutJS是否创建了一个可订阅事件.
Basically, I'm trying to find out if there is a subscribe-able event that KnockoutJS creates after a template render when using something like jQuery templates.
我将使用内置的"afterRender",但是我发现,如果清除了可观察数组,则不会触发.我构建了这个演示来说明该问题: http://jsfiddle.net/farina/YWfV8/1/.
I'd use the built-in "afterRender" but I found out that it doesn't fire if the observable array is cleared. I built this demo to illustrate that problem: http://jsfiddle.net/farina/YWfV8/1/.
此外,我知道我可以编写一个自定义处理程序...但这似乎对我所需要的确实不必要.
Also, I'm aware that I could write a custom handler...but that seems really unnecessary for what I need.
我只希望模板完成渲染后触发一个事件.
I just want one event that fires after the template finishes rendering.
推荐答案
昨天晚上,我的同事实际上使用我们回家之前玩的东西解决了这个问题.
My colleague actually solved this last night using something we were playing with before I went home.
因此带有事件"afterRender","afterAdd"和"beforeRemove"的整个问题"是,它们与"foreach"绑定一起的行为不同. KnockoutJS非常好,可以在他们的页面上告诉您,但是无论出于什么原因,直到我在实践中看到它,我才真正陷入沉迷.
So the whole "problem" with the events "afterRender", "afterAdd", and "beforeRemove" is that they act differently in conjunction with a "foreach" binding. KnockoutJS is nice enough to tell you this on their page, but for whatever reason it didn't actually sink in for me until I saw it in practice.
真正有效的方法是取消整个"foreach"绑定,并使用Knockout的本机数据"绑定,如下所示:
What really works is to scrap the whole "foreach" binding and use Knockout's native "data" bind like this:
data-bind="template: { name: 'item-template', data: items, afterRender: caller }"
然后,"afterRender"的工作原理与名称相同.
Then "afterRender" works exactly as the name suggests.
给我的印象是,您不能在没有foreach的情况下迭代集合并呈现新的UI,但是这些示例说明了它确实可以工作.
I was under the impression that you couldn't iterate the collection and render new UI without foreach, but these examples illustrate that it does work.
-
http://jsfiddle.net/farina/kuFx2/1/ (使用对象数组样式ViewModel)
http://jsfiddle.net/farina/kuFx2/1/ (Using object array style ViewModel)
http://jsfiddle.net/farina/QtZm2/1/ (使用函数样式ViewModel)
http://jsfiddle.net/farina/QtZm2/1/ (Using function style ViewModel)
我为两种ViewModel样式都做了一个示例,因为有时我需要其中一种.
I made an example for both ViewModel styles because I sometimes need one or the other.
感谢丹的帮助!
这篇关于模板渲染后的KnockoutJS绑定事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!