简体   繁体   中英

Meteor helper functions versus variables?

I was trying to display a count of all online users on my website, and installed the meteor-user-status plugin to help with this. I thought all I had to do was add a template helper

Template.header.helpers({
    numOnline: Meteor.users.find({"status.online":true}).count()
});

like so, and include the {{numOnline}} variable in my header template. But, for some reason, that resulted in always displaying 0 users online. However, when I simply ran the method Meteor.users.find({"status.online":true}).count() in the javascript console, it gave the correct amount of users online.

After messing around with it a bit, I got it to work by wrapping it in a function:

Template.header.helpers({
    numOnline: function(){
        return Meteor.users.find({"status.online":true}).count();
    }
});

This change makes it work perfectly, but I have no clue why. Can someone explain why it was necessary to wrap it in a function?

Adding Christian Fritz, The only reason I think this can be happening is in the first case numOnline: Meteor.users.find({"status.online":true}).count() the collection is not ready at the point of evaluation of the template and assign 0 or empty array [] since is what the subscription return, and in the second case since is a function will react whenever a change occurs in a collection, so that's why will have the value a soon the collection get fill with the subscription and the function will get execute whit the most recent value.Just my two cents. Please correct me if I'm wrong.

Well, that's just what it is (and the documentation tells you so, too). The reason why this need to be a function is reactivity: in order to reevaluate the piece of code at a later point in time (when a reactive datasource has changed value), you need to have a function.

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