在我的模板中,我有这个 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.
更多推荐
如何避免流星助手多次运行
发布评论