Can't update a template


#1

Hi:

I’m doing a simple app that have a function that I want to use from several other parts.

Then, I’ve something like that:

Template.main.helpers({
sortedWinners: function (event, template) {
return calculateWinners();

calculateWinners call the function that I mentioned before, and this work ok when the pages es shown.

Then I’ve also a button, to try again (pressing this button the function is called again and return results), but they are not shown in the html.

The code is something like:

Template.main.events({
‘click button’: function (event, template) {

  return calculateWinners();

}

Why the template don’t get updated in this second case?

Thanks for any hint.


#2

Is your function just returning a result? Your template is not being updated because you’re not using reactive variables. Try using reactive/session vars instead.

var calculateWinners = function () {
    var winners;
    // whatever logic you have
    Session.set('currentWinners', winners);
}

Template.main.helpers({
    sortedWinners: function () {
        return Session.get('currentWinners');
    }
});

Template.main.events({
    'click button': function () {
        calculateWinners();
    }
});

#3

Thanks for your help, I read before about sessions but I’m not sure of corrently understand the complete stuff.

For example, your example works to me, except that I must add a “calculateWinners()” before the “return Session.get(‘currentWinners’);” in the template main help to have the number displayed with the page first load or is reloaded.

The thing that I do not understand clearly is what does the “return Session.get(‘currentWinners’);” in the helper.

Thanks for your time!


#4

You should change the way you think about displaying data on your page. I’m not sure what your calculateWinners() function does - but if you get your data from a Mongo cursor (like People.find({ winner: true }) or something - you can just put that code in your helper, and it will be re-run every time there is a change on your cursor. So no need for any function calling or clicking a button to re-calculate.


#5

Ahh, will try at this way.

The function here only calculates 6 random numbers between 00 and 45, nothing more. No Mongo involved.

But I put the function separated thinking that i can use it from the template helper and when the user want to press a button to calculate new 6 random numbers.


#6

You can still do that, just don’t return a result. Instead, set a session/reactive variable like above.


#7

Thanks you for your help, I will try some more options to understand better.

Cheers.