模板渲染后的 KnockoutJS 绑定事件 [英] KnockoutJS bind event after template render

查看:28
本文介绍了模板渲染后的 KnockoutJS 绑定事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了一段时间,我非常有信心这是一个新问题,而不是像标题所暗示的那样重复.:)

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/ (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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆