Best way to prevent a template helper to be rerun

2019-02-19 08:22发布

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>

I have autopublish enabled.

  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;
    }
  });

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.

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

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

1条回答
男人必须洒脱
2楼-- · 2019-02-19 08:56

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
  });
}
查看更多
登录 后发表回答