简体   繁体   English

流星辅助函数与变量?

[英]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. 我试图显示我网站上所有在线用户的数量,并安装了meteor-user-status插件来解决此问题。 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. 像这样,并在我的标题模板中包含{{numOnline}}变量。 But, for some reason, that resulted in always displaying 0 users online. 但是,由于某种原因,这导致始终在线显示0个用户。 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. 但是,当我在javascript控制台中简单运行方法Meteor.users.find({“ status.online”:true})。count()时,它为在线用户提供了正确的数量。

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. 添加Christian Fritz,我认为可能会发生的唯一原因是在第一种情况下numOnline: Meteor.users.find({"status.online":true}).count()集合在评估时尚未准备好模板,并分配0或空数组[]因为这是订阅返回的内容,在第二种情况下,是,当集合中发生更改时,函数将做出反应,因此这就是为什么该值很快就会被集合填充与订阅和功能将执行最新的价值。仅我的两分钱。 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. 之所以需要将其作为函数,是因为它具有反应性:为了在以后的某个时间点(当反应性数据源更改值时)重新评估代码段,您需要具有一个函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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