如何在#each完成后执行回调?

时间:2015-09-08 15:25:52

标签: javascript meteor spacebars

我在#each完成后遇到回调问题。我有一个名为“content”的模板:

<template name="content">
{{#if Template.subscriptionsReady}}
    {{#each currentData}}
        <div data-cid="{{this._id}}"></div>
    {{/each}}
{{else}}
    Loading...
{{/if}}
</template>

首先我等待订阅,如果可用,我会使用{{#each}}遍历我的收藏集并附加div。我需要的是一种回调,用于完成for-each循环(换句话说就是DOM就绪)。

Template.content.onRendered()

- &GT;触发早期

我还尝试在{{each}}之后添加图片,并在其onload中触发一个函数,如下所示:

<img style="height:0;width:0" src="*mysource*" onload="callback()">

- &GT;有时工作但不可靠的某种方式

有没有办法获得此回调?我不担心改变这个模板的结构,如果它带来了解决方案。

3 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,经过大量搜索后发现了以下解决方案。我尝试使用onRenderedeach和其他技巧,但都没有奏效。这可以被视为更多的黑客,但有效。不幸的是,我不记得我最初在哪里找到了这个解决方案。

从模板开始,但在<template name="content"> {{#if Template.subscriptionsReady}} {{#each currentData}} <div data-cid="{{this._id}}"></div> {{/each}} {{doneTrigger}} {{else}} Loading... {{/if}} </template> 后添加模板标记。

Template.content.helpers({
  doneTrigger: function() {
    Meteor.defer(function() {
      // do what you need to do
    });
    return null;
  }
});

然后定义一个返回null的帮助器。

Meteor.defer()

您可以详细了解setTimeout here,但这相当于使用0毫秒context

答案 1 :(得分:0)

您还可以使用子模板并计算渲染的子模板数量。如果此数字是集合中的项目数,则全部呈现。

<template name="content">
{{#if Template.subscriptionsReady}}
    {{#each currentData}}
        {{> showData}}
    {{/each}}
{{else}}
    Loading...
{{/if}}
</template>

<template name="currentData">
  <div data-cid="{{this._id}}"></div>
</template>

然后,初始化一个反应变量并跟踪它:

var renderedCount = new ReactiveVar(0);

Tracker.autorun(function checkIfAllRendered() {
  if(renderedCount.get() === currentData.count() && renderedCount.get() !== 0) {
    //allDataRendered();
  }
});

渲染currentData模板时,将其递增,并在销毁时递减。

Template.currentData.onRendered(function() {
  renderedCount.set(++renderedCount.curValue);
});

Template.currentData.onDestroyed(function() {
  renderedCount.set(--renderedCount.curValue);
});

答案 2 :(得分:-1)

一种可能更简单的方法 - 在#each块周围创建一个模板,然后获得onRendered事件:

HTML:

<template name="content">
{{#if Template.subscriptionsReady}}
    {{> eachBlock}}
{{else}}
    Loading...
{{/if}}
</template>

<template name="eachBlock">
{{#each currentData}}
    <div data-cid="{{this._id}}"></div>
{{/each}}
</template>

JS:

Template.eachBlock.onRendered(function(){
  console.log("My each block should now be fully rendered!");
});