简体   繁体   中英

Calculations using handlebars in Meteor

I have upvotes and downvotes and they are both in the collections and are displayed in the template as {{upvotes}} and {{downvotes}} .

So if I were to have a 3rd display that shows total votes, should I do it via a helper like the below (not working by the way):

In the helper.js:

Template.registerHelper('totalvotes', function(upvotes, downvotes) {
    var totalvotes = upvotes + downvotes;
    return totalvotes;
});

In the html:

{{ totalvotes "Vote"}}


I remembered something about performance and not calculating all the fields on the client level. In that case, would it be better to have an increment in the main object collection instead by adding in a totalvotes field than having a helper in the client? (Do include a rough form of suggested codes). Thanks!

For example in collection (fields):

upvotes: 0 
downvotes: 0 

Then the increment logic

$inc: {upvotes: 1}
$inc: {downvotes: 1}

to

upvotes: 0 
downvotes: 0 
totalvotes: 0

$inc: {upvotes: 1}
$inc: {downvotes: 1}
$inc: {totalvotes: 1}

You shouldn't take this recommendation too literally, because it really depends on what you're doing.

For this particular case, I think it's much better to do the math with a helper on the client side (that's just an extra call to a helper that'll do some very simple processing) than adding an extra denormalized field on the database, which would add a bigger overall overhead (storage on disk, memory space, network data).


for your inspiration:

"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%." -- Donald Knuth

I agree with @dooart answer.

Concerning your helper not working, I would advise to store upvotes and downvotes in pageSession reactive variables (using reactive-dict ).

That way, you don't have to pass 2 parameters to your helper and you get a reactive vote count: each of your downvotes, upvotes and totalvotes helper just return the related variable (or the sum of them in totalvotes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM