Best way to prevent a template helper to be rerun when it is unnecessary?

怎甘沉沦 提交于 2019-12-30 11:12: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:


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


来源:https://stackoverflow.com/questions/26362972/best-way-to-prevent-a-template-helper-to-be-rerun-when-it-is-unnecessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!