我试图阻止在不必要的时候重新运行模板帮助程序。我制作了一个简单的应用程序来说明这种行为:
假设我想显示一些只包含标题和描述的项目。
<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;
}
});
当仅对标题字段进行新的更新时,您可以看到描述帮助程序将重新运行。我试图实现的是,只有当描述字段有了新值时,而不是每次文档中的字段发生更改时,才重新运行此帮助程序。
由于{{#constant}}和{{#isolate}}被弃用,我如何在最新的Meteor版本中获得这种行为?
注意1:创建一个包含描述的新子模板并不能解决问题。
我会避免模板助手中的副作用。相反,我会使用自动运行:
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
});
}