0

我有这个代码:

Template.temp.rendered = function () {
    console.log('temp rendered');
}

仅在网站初始化时记录。

但我做这样的事情:

more = function () {
    Meteor.subscribe('Videos', Session.get('more_info'));
}

当我调用 more(); 即使模板 dom 使用新文档更新,它也不会记录“临时渲染”。还尝试了类似的东西:

Template.temp.rerendered = function () {
    console.log('temp re rendered');
}

这没用; 我如何知道 A 模板是否被重新渲染?

目前我正在做这样的事情

$('#list').bind("DOMSubtreeModified",function(){
    console.log('template modified'}
    //this logs like 200 times, every time the template is re rendered
)

我怎样才能以流星的方式做到这一点?

列表模板:

<template name="list">
    {{#each list}}
        <a id="{{_id}}" href="/{{category}}/{{_id}}" title="{{vTitle}}">
            {{vTitle}}
        </a>
    {{/each}}
</template>

帮手:

Template.list.helpers({
  list : function () {
     return Videos.find({},{sort : {date : -1}});
  }
})

试过(不工作):

Template.list.rendered = function () {    
  this.autorun(function() {
    Videos.find();
    console.log('template re rendered');
  });
}

首选解决方案(来自@richsilv):

Template.list.rendered = function () {    
  this.autorun(function() {
    Videos.find().count();
    console.log('template re rendered');
  });
}

如果您每次渲染模板时都需要调用一个函数并且不想注册自动运行,那么@Peppe LG 的解决方案也很好。

4

2 回答 2

2

是的,rendered回调仅在模板最初呈现时触发一次,而不是在模板由于其依赖的计算而更改时被触发无效。

Meteoric 做事的方法是添加一个this.autorun到渲染的回调,它依赖于导致模板重新渲染的同一件事(即集合find上的a 或其他)。Videos这样你就是:

  1. 将您的反应性绑定到数据源而不是 DOM,这除了从概念角度更明智之外,还意味着您不会在每次模板发生任何更改时都运行大量不必要的计算,这非常重要,如果它依赖于多个数据源(autorun如有必要,您可以为每个源设置不同的数据源)。
  2. 仍然利用模板autorun在拆除时停止声明的块的能力this,这消除了手动停止它们的需要,以避免加载大量浮动的、未使用的自动运行占用 CPU 和内存。
于 2014-12-16T11:55:06.290 回答
1

从 Blaze (Meteor 0.8.0) 开始,模板永远不会重新渲染。相反,使用细粒度更新。如果您需要知道模板的某个部分何时发生更改,请尝试将该部分放入另一个模板中,并使用该模板的渲染功能。例如,如果您有以下模板:

<template name="myTemplate">
    {{#if reactiveCondition}}
        <p>The reactive condition is true!</p>
    {{/if}}
</template>

并且您希望在呈现段落时发生一些事情,您需要执行以下操作:

<template name="myTemplate">
    {{#if reactiveCondition}}
        {{> paragraph}}
    {{/if}}
</template>
<template name="paragraph">
    <p>The reactive condition is true!</p>
</template>
Template.paragraph.rendered = function(){
    console.log("The paragraph rendered!")
}

相同的原理可以应用于游标。例如,以下模板:

<template name="myTemplate">
    {{#each getCursor}}
        <p>A document in the cursor!</p>
    {{/each}}
</template>

必须写成:

<template name="myTemplate">
    {{#each getCursor}}
        {{> document}}
    {{/each}}
</template>
<template name="document">
    <p>A document in the cursor!</p>
</template>
Template.document.rendered = function(){
    console.log("A document is rendered!")
}
于 2014-12-16T11:59:23.387 回答