【问题标题】:Using Meteor.users() in a template helper在模板助手中使用 Meteor.users()
【发布时间】:2014-05-12 15:19:28
【问题描述】:

我在从 Meteor 0.8.0 的模板帮助程序中获取用户配置文件数据时遇到问题。这段代码在以前的版本中运行良好,但自从今天早上升级后它就坏了。我最初认为这是模板助手运行两次的问题,但当我深入研究时,我发现问题比这更微妙。

在模板帮助器“findClientLiason”下方被调用了两次(它的输出在控制台中记录了 2 次)。用户第一次将显示为“未定义”,第二次正确的用户对象将以我期望的方式出现。两次“clientLiason”都会正确输出。

对我来说最有趣的是,如果我删除 'var user = Meteor.users.findOne({_id: clientLiason});'调用 findOne 调用助手只调用一次。

在我看来,对 Meteor.users 集合的调用会强制对数据库进行另一次调用。而且它第一次调用它时 Meteor.users 集合是空的。

我有如下所示的发布和订阅。我正在使用 Iron Router 全局 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;
    }
});

【问题讨论】:

    标签: collections meteor meteor-blaze meteor-helper


    【解决方案1】:

    这是有道理的,因为发生的情况是,首先在页面加载并且用户集合为空时呈现模板,然后随着数据的变化重新呈现模板(例如,本地 mongo 集合被填充) .

    您应该编写模板以期望在没有数据的情况下开始加载页面。我会将助手更改为这样的:

    findClientLiaison: function(clientLiaison) {
      var user = Meteor.users.findOne(clientLiaison);
      if (user) {
        return user.profile.name;
      }
      return "no data yet";
    }
    

    【讨论】:

    • 好的,看起来它已经修复了。非常感谢。不过有几个问题。这是否随着 Blaze 的发布而改变?此外,代码重复这样两次是否有任何问题,或者这只是它如何工作的函数。再次感谢。
    • 您一直需要注意初始加载状态,但 Blaze 改变了助手的工作方式,因此可能与此有关。
    • @yankeyhotel 为什么使用 findOne 而不是 find 有意义?看到这个reproducible example
    猜你喜欢
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 2013-06-19
    • 2014-06-20
    • 2014-08-12
    • 2014-06-11
    • 1970-01-01
    • 2015-01-15
    相关资源
    最近更新 更多