如何避免流星助手多次运行 [英] How to avoid Meteor helpers run multiple times

查看:28
本文介绍了如何避免流星助手多次运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模板中,我有这个 HTML:

In my template I have this HTML:

<input id="name"   type="text" value="{{card.name}}">
<input id="prefix" type="text" value="{{card.prefix}}">
<input id="phone"  type="tel"  value="{{card.phone}}">

和这个 JavaScript

and this JavaScript

Template.cardForm.helpers({
  card: function() {
    return getCard();
  }
});

var getCard = function() {
    console.log("I'm here !!!");
    return Cards.findOne({_id: cardId});
} 

当我运行我的应用程序时,console.log 显示我在这里!!!"3 次,我认为 Ecards.findOne() 执行了 3 次.

When I run my app, the console.log shows "I'm here !!!" 3 times, and I think that Ecards.findOne() is executing 3 times.

我怎样才能避免那些额外的电话?

How can I Avoid those extra calls?

我想获取卡片对象以填充 {{card.name}}{{card.prefix}}{{card.phone}},但只能调用一次 getCard().

I want to get card object in order to fill {{card.name}}, {{card.prefix}} and {{card.phone}}, but only with one call to getCard().

推荐答案

card 助手被执行多次,因为 card 在评估的模板代码中出现不止一次.

The card helper is executed several times since card is present in evaluated template code more than once.

在您面临的场景中避免重复调用的一种模式是使用 #with:

A pattern to avoid duplicate calls in scenarios like the one you're facing is to use #with:

{{#with card}}
  <input id="name"   type="text" value="{{name}}">
  <input id="prefix" type="text" value="{{prefix}}">
  <input id="phone"  type="tel"  value="{{phone}}">
{{/with}}

这将调用 card 一次,然后在其结果的上下文中运行嵌套代码.

This will call card once and then run the nested code in the context of its result.

这篇关于如何避免流星助手多次运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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