模板渲染后 KnockoutJS 绑定事件

发布于 2025-01-05 17:06:13 字数 385 浏览 0 评论 0原文

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

基本上,我试图找出当使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黯淡〆 2025-01-12 17:06:13

我的同事昨晚实际上用我回家前玩的东西解决了这个问题。

因此,事件“afterRender”、“afterAdd”和“beforeRemove”的整个“问题”在于它们与“foreach”绑定结合时的行为不同。 KnockoutJS 足够好,可以在他们的 页面 上告诉你这一点,但无论出于什么原因它没有'在我在实践中看到它之前,我并没有真正理解它。

真正有效的是废弃整个“foreach”绑定并使用 Knockout 的本机“data”绑定,如下所示:

data-bind="template: { name: 'item-template', data: items, afterRender: caller }"

然后“afterRender”的工作原理正如其名称所示。

我的印象是,如果没有 foreach,就无法迭代集合并呈现新的 UI,但这些示例表明它确实有效。

我制作两种 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:

data-bind="template: { name: 'item-template', data: items, afterRender: caller }"

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.

I made an example for both ViewModel styles because I sometimes need one or the other.

Thanks for the help Dan!!

柠檬心 2025-01-12 17:06:13

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文