防止不必要的模板帮助程序重新运行的最佳方法? [英] Best way to prevent a template helper to be rerun when it is unnecessary?

查看:73
本文介绍了防止不必要的模板帮助程序重新运行的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图防止不必要的模板帮助程序重新运行.我做了一个简单的应用程序来说明这种行为:

I'm trying to prevent a template helper to be rerun when it is unnecessary. I made a simple application to illustrate this behavior:

假设我要显示一些仅包含标题和描述的项目.

Let's say I want to display some items that contain only a title and a description.

<template name="Tests">

  {{#each items}}
    {{> TestsItems}}
  {{/each}}

</template>


<template name="TestsItems">

  <div class="title">{{title}}</div>
  <div class="description">{{description}}</div>

</template>

我已启用自动发布.

  Template.Tests.helpers({
    items: function () {
      return Items.find();
    }
  });

  Template.TestsItems.helpers({
    description: function () {
      // I'm using this helper to do some updates
      // on a jQuery plugin when the description field change.
      // see example 1: https://github.com/avital/meteor-ui-new-rendered-callback/

      console.log("The description is run");

      return this.description;
    }
  });

仅在标题字段上进行新更新时,您可以看到重新运行了描述帮助器.我要实现的目标是仅在description字段有新值时才重新运行此帮助程序,而不是在文档中每次更改字段时都重新运行.

When a new update is made on the title field only, you can see that the description helper is rerun. What I'm trying to achieve is to only rerun this helper when there is a new value for the description field and not every time a field has changed in the document.

不推荐使用{{#constant}}和{{#isolate}},如何在最新的Meteor版本中获得这种行为?

As {{#constant}} and {{#isolate}} are deprecated, how can I get this behavior in the latest Meteor versions?

注释1 :创建一个包含说明的新子模板不能解决问题.

Note 1: Create a new subtemplate including the description does not fix the problem.

推荐答案

我会避免模板助手中的副作用.相反,我会使用自动运行:

I would avoid side effects in template helpers. Instead I would use an autorun:

Template.TestItems.rendered = function () {
  var _id = this.data._id;
  this.autorun(function () {
    // Select only the description field, so that we only
    // trigger a re-run if the description field changes
    var description = Items.findOne(_id, {fields: {description: 1}}).description;

    // update the JQuery plugin
  });
}

这篇关于防止不必要的模板帮助程序重新运行的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆