从 template.onRendered 访问 Meteor.users [英] access Meteor.users from template.onRendered

查看:31
本文介绍了从 template.onRendered 访问 Meteor.users的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行这段代码

Template.addPost.onRendered ->
@$('#name').val(Meteor.user().profile.name)

但似乎模板在 Users collection 填充到客户端之前呈现.因此返回我

But it seems that the template is rendered earlier than Users collection gets populated on the Client. Thus returning me

Cannot read property 'profile' of undefined

我该如何解决这个问题?

How do I tackle this?

推荐答案

您可以通过 自动运行:

Template.addPost.onRendered ->
  @autorun (c) ->
    # extract the name in a safe way
    {name} = Meteor.user()?.profile

    # once a name has been found, update the DOM and stop the autorun
    if name
      # note that name is an id so we don't need @$
      $('#name').val name
      c.stop()

我们还利用了 coffeescript 的存在运算符来安全地提取名称值.在 javascript 中,这个解决方案看起来像这样:

We are also taking advantage of coffeescript's existential operator to safely extract the name value. In javascript this solution would look something like this:

Template.addPost.onRendered(function() {
  this.autorun(function(c) {
    var user = Meteor.user()
    var name = user && user.profile && user.profile.name;
    if (name) {
      $('#name').val(name);
      c.stop();
    }
  });
});

这篇关于从 template.onRendered 访问 Meteor.users的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆