0

Why does the template get rendered the number of times that correlates with the Each in my template.

<template name="carousel">
<div class="pikachoose">
<ul class="carousel" >
{{#each article}}
    <li><a href="#"><img src="{{image}}" width="500" height="250"  alt="picture"/></a><span>{{caption}}</span></li>
{{/each}}
   </ul>
   </div>

</template>

Template.carousel.article = function () {
return News.find({},{limit: 3});

}

Template.carousel.rendered = function() {
//$(".pika-stage").remove();
alert($(".carousel").html());
//$(".carousel").PikaChoose({animationFinished: updateNewsPreview});
}

In this case it would alert 3 times.

4

2 回答 2

1

这就是 Meteor 处理数据更新的方式。您的article数据函数返回要在模板中使用的游标。最初,光标为空,从服务器中提取数据,一次一篇文章。每次获取一篇文章时,光标的内容都会改变(它现在多了一篇文章),因此响应式article方法会导致模板重新呈现。

 


 

如果您需要确保您的代码只运行一次,则根据您的需要有多种可能性。

最简单的方法就是使用created而不是rendered.

如果你修改 DOM 元素,你也可以标记你修改的元素,这样你就不会处理它们两次:

Template.carousel.rendered = function() {
    _.each(this.findAll('.class'), function(element){
        if($(element).data('modified')) return;
        $(element).data('modified', true);
        ...
    });
};

您可以禁用光标的反应性,尽管这是一个可悲的解决方案:

Articles.find(..., {reactive: false});

最具侵入性,但也最通用的是观察数据何时满载:

Deps.autorun(function() {
    Meteor.subscribe('articles', {
        ready: function() {
            ...
        },
    });
});
于 2013-07-30T05:48:38.920 回答
0

该问题可能与.rendered回调的使用有关。每次循环运行时,DOM 都会更新,因此回调将再次运行。

当我过去遇到这个问题时,我发现尽可能使用 Meteor 事件处理程序很有帮助,以消除像这样的加载顺序问题。在这种情况下,也许您可​​以尝试超时,以便仅在 DOM 安静一段时间后才运行.remove()and调用。.PikaChoose()希望这对你有用。

于 2013-07-30T03:23:44.790 回答