O.Perez
O.Perez

Reputation: 31

How to avoid Meteor helpers run multiple times

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}}">

and this JavaScript

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

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

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?

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

Upvotes: 3

Views: 311

Answers (1)

MasterAM
MasterAM

Reputation: 16488

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

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

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

Upvotes: 3

Related Questions