在 Meteor 中使用车把进行计算
Calculations using handlebars in Meteor
我有赞成票和反对票,它们都在集合中,并在模板中显示为 {{upvotes}}
和 {{downvotes}}
。
因此,如果我要有一个显示总票数的第三个显示器,我是否应该通过如下所示的助手来完成(顺便说一句,不工作):
中helper.js:
Template.registerHelper('totalvotes', function(upvotes, downvotes) {
var totalvotes = upvotes + downvotes;
return totalvotes;
});
中html:
{{ totalvotes "Vote"}}
我想起了一些关于性能的事情,而不是计算客户端级别的所有字段。在这种情况下,通过添加 totalvotes 字段来增加主对象集合是否比在客户端中使用助手更好? (请包含建议代码的粗略形式)。谢谢!
例如在集合(字段)中:
upvotes: 0
downvotes: 0
然后递增逻辑
$inc: {upvotes: 1}
$inc: {downvotes: 1}
到
upvotes: 0
downvotes: 0
totalvotes: 0
$inc: {upvotes: 1}
$inc: {downvotes: 1}
$inc: {totalvotes: 1}
你不应该太从字面上理解这个建议,因为它真的取决于你在做什么。
对于这种特殊情况,我认为在客户端使用助手进行数学运算(这只是对助手的额外调用,它会执行一些非常简单的处理)比添加额外的非规范化字段要好得多在数据库上,这会增加更大的总体开销(磁盘存储、内存 space、网络数据)。
你的灵感:
"Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%." -- 唐纳德·高德纳
我同意@dooart 的回答。
关于您的助手不工作,我建议将赞成票和反对票存储在 pageSession 反应变量中(使用 reactive-dict)。
这样一来,您就不必将 2 个参数传递给您的助手,并且您会得到一个反应性投票计数:您的每一个反对票、赞成票和总票数助手只是 return 相关变量(或总和他们的总票数)
我有赞成票和反对票,它们都在集合中,并在模板中显示为 {{upvotes}}
和 {{downvotes}}
。
因此,如果我要有一个显示总票数的第三个显示器,我是否应该通过如下所示的助手来完成(顺便说一句,不工作):
中helper.js:
Template.registerHelper('totalvotes', function(upvotes, downvotes) {
var totalvotes = upvotes + downvotes;
return totalvotes;
});
中html:
{{ totalvotes "Vote"}}
我想起了一些关于性能的事情,而不是计算客户端级别的所有字段。在这种情况下,通过添加 totalvotes 字段来增加主对象集合是否比在客户端中使用助手更好? (请包含建议代码的粗略形式)。谢谢!
例如在集合(字段)中:
upvotes: 0
downvotes: 0
然后递增逻辑
$inc: {upvotes: 1}
$inc: {downvotes: 1}
到
upvotes: 0
downvotes: 0
totalvotes: 0
$inc: {upvotes: 1}
$inc: {downvotes: 1}
$inc: {totalvotes: 1}
你不应该太从字面上理解这个建议,因为它真的取决于你在做什么。
对于这种特殊情况,我认为在客户端使用助手进行数学运算(这只是对助手的额外调用,它会执行一些非常简单的处理)比添加额外的非规范化字段要好得多在数据库上,这会增加更大的总体开销(磁盘存储、内存 space、网络数据)。
你的灵感:
"Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%." -- 唐纳德·高德纳
我同意@dooart 的回答。
关于您的助手不工作,我建议将赞成票和反对票存储在 pageSession 反应变量中(使用 reactive-dict)。
这样一来,您就不必将 2 个参数传递给您的助手,并且您会得到一个反应性投票计数:您的每一个反对票、赞成票和总票数助手只是 return 相关变量(或总和他们的总票数)