在模板帮助程序中使用Meteor.users()
问题描述:
我在从Meteor 0.8.0的模板帮助程序中获取用户配置文件数据时遇到问题。此代码在以前的版本中运行良好,但自今天早上升级以来已损坏。我原本以为这是一个模板助手运行两次的问题,但是随着我的深入,我发现问题比这更微妙。在模板帮助程序中使用Meteor.users()
在模板助手'findClientLiason'下面调用两次(它的输出在控制台中记录了两次)。用户第一次第一次显示为“未定义”,正确的用户对象将按照我期望的方式出现。 'clientLiason'两次都会正确输出。
我最感兴趣的是,如果我删除'var user = Meteor.users.findOne({_ id:clientLiason});'调用getOne调用帮助器只调用一次。
它看起来像对Meteor.users集合的调用强制另一个数据库调用。第一次它称之为Meteor.users集合是空的。
我有如下所示的发布和订阅。我正在使用铁路路由器全局waitOn()函数,但我想知道是否应该在早些时候加载Meteor.users集合?
任何想法,将不胜感激。再次感谢。
publications.js
Meteor.publish('allUsers', function() {
return Meteor.users.find();
});
router.js
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
waitOn: function() {
return [
Meteor.subscribe('clientsActive'),
Meteor.subscribe('allUsers'),
Meteor.subscribe('notifications')
];
}
});
clientItem.html
<template name="clientItem">
{{findClientLiason clientLiason}}
</template>
clientItem.js
Template.clientItem.helpers({
findClientLiason: function(clientLiason) {
var user = Meteor.users.findOne({_id: clientLiason});
console.log(clientLiason);
console.log(user);
return user.profile.name;
}
});
答
这是有道理的,因为发生的事情是,第一模板被渲染时的页面加载和用户集合为空,然后它被重新呈现为数据的变化(例如。当地的mongo收藏已满)。
你应该编写你的模板,以期在没有数据的页面加载时开始。我会改变帮手这样的事情:
findClientLiaison: function(clientLiaison) {
var user = Meteor.users.findOne(clientLiaison);
if (user) {
return user.profile.name;
}
return "no data yet";
}
好吧,看起来像它修复它。非常感谢。但有几个问题。随着Blaze的发布,这个变化了吗?另外,这样的代码是否有任何问题重复这样两次,或者这只是它的工作原理的一个函数。再次感谢。 – yankeyhotel
您一直不得不关注初始加载状态,但Blaze改变了助手的工作方式,所以它可能与此有关。 – Rahul
@yankeyhotel为什么使用'findOne'而不是'find'有意义?看到这个[可重现的例子](https://gist.github.com/gentunian/c0a3d8a755c86636a93d) – Sebastian