我在 #each
完成后遇到回调问题。我有一个名为“content”的模板:
<template name="content">
{{#if Template.subscriptionsReady}}
{{#each currentData}}
<div data-cid="{{this._id}}"></div>
{{/each}}
{{else}}
Loading...
{{/if}}
</template>
首先,我等待订阅,当订阅可用时,我使用 {{#each}}
遍历我的 Collection 并附加 div
。我需要的是一种在 for-each 循环完成时的回调(换句话说,DOM 就绪)。
Template.content.onRendered()
->提前触发
我还尝试在 {{each}} 之后附加一个图像并在其 onload
中触发一个函数,如下所示:
<img style="height:0;width:0" src="*mysource*" onload="callback()">
-> 有时确实有效,但不知何故不可靠
有没有办法得到这个回调?如果能带来解决方案,我不怕更改此模板的结构。
最佳答案
当 Spacebars {{#each}}
block 已将每个项目迭代到 DOM 中时,没有简单的方法来获得通知。
最好的解决方案是使用另一种响应式(Reactive)计算 (Tracker.autorun
) 来观察您的(响应式(Reactive))当前数据。
每次修改当前数据(可能是游标)时,您都可以使用 Tracker.afterFlush
在所有其他响应式(Reactive)计算完成后运行任意代码来执行它们的工作。
{{#each}}
block 是其中一种计算,其作用是监听您作为参数提供给它的响应式数据源并重新呈现其 Template.contentBlock
迭代从源中获取的项目的次数,当前项目作为当前数据上下文。
通过监听与 {{#each}}
block 助手完全相同的响应式(Reactive)数据源并在它完成自己的响应式(Reactive)计算后运行您的代码,您可以获得实际请求的行为而无需依靠一些奇怪的技巧。
下面是这个模式的完整实现:
JS
Template.content.helpers({
currentData: function(){
return Template.currentData();
}
});
Template.content.onRendered(function(){
this.autorun(function(){
var cursor = Template.currentData();
// we need to register a dependency on the number of documents returned by the
// cursor to actually make this computation rerun everytime the count is altered
var count = cursor.count();
//
Tracker.afterFlush(function(){
// assert that every items have been rendered
console.log(this.$("[data-cid]") == count);
}.bind(this));
}.bind(this));
});
关于javascript - #each 完成后如何执行回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32461639/