模板渲染后 KnockoutJS 绑定事件
我已经搜索了一段时间,并且我非常有信心这是一个新问题,而不是像标题所暗示的那样重复。 :)
基本上,我试图找出当使用 jQuery 模板之类的东西时,KnockoutJS 在模板渲染后是否创建了一个可订阅的事件。
我会使用内置的“afterRender”,但我发现如果可观察数组被清除,它不会触发。我构建了这个演示来说明该问题: http://jsfiddle.net/farina/YWfV8/1/< /a>.
另外,我知道我可以编写一个自定义处理程序......但这对于我的需要来说似乎确实没有必要。
我只想要一个在模板完成渲染后触发的事件。
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. :)
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的同事昨晚实际上用我回家前玩的东西解决了这个问题。
因此,事件“afterRender”、“afterAdd”和“beforeRemove”的整个“问题”在于它们与“foreach”绑定结合时的行为不同。 KnockoutJS 足够好,可以在他们的 页面 上告诉你这一点,但无论出于什么原因它没有'在我在实践中看到它之前,我并没有真正理解它。
真正有效的是废弃整个“foreach”绑定并使用 Knockout 的本机“data”绑定,如下所示:
然后“afterRender”的工作原理正如其名称所示。
我的印象是,如果没有 foreach,就无法迭代集合并呈现新的 UI,但这些示例表明它确实有效。
http://jsfiddle.net/farina/kuFx2/1/ (使用对象数组样式 ViewModel)
http://jsfiddle.net/farina/QtZm2/1/ (使用函数样式 ViewModel)
我制作两种 ViewModel 样式的示例,因为我有时需要其中一种。
感谢丹恩的帮助!!
My colleague actually solved this last night using something we were playing with before I went home.
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.
What really works is to scrap the whole "foreach" binding and use Knockout's native "data" bind like this:
Then "afterRender" works exactly as the name suggests.
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/ (Using object array style ViewModel)
http://jsfiddle.net/farina/QtZm2/1/ (Using function style ViewModel)
I made an example for both ViewModel styles because I sometimes need one or the other.
Thanks for the help Dan!!
beforeRemove
是您要找的吗?我不确定你想要实现什么行为。请查看此示例:http://jsfiddle.net/romanych/YWfV8/8/这是你想要的还是不想要的?
Is
beforeRemove
is what you are looking for? I am not sure what behaviour you want to achieve. Please checkout this sample: http://jsfiddle.net/romanych/YWfV8/8/Is it what you want or not?