I need to execute this piece of code
我需要执行这段代码
Template.addPost.onRendered ->
@$('#name').val(Meteor.user().profile.name)
But it seems that the template is rendered earlier than Users collection
gets populated on the Client. Thus returning me
但似乎模板的呈现时间早于在客户端上填充的Users集合。从而归还我
Cannot read property 'profile' of undefined
How do I tackle this?
我该如何解决这个问题?
1 个解决方案
#1
You can wait for the user to be loaded via an autorun:
您可以等待通过自动运行加载用户:
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()
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:
我们还利用coffeescript的存在运算符来安全地提取名称值。在javascript中,此解决方案看起来像这样:
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();
}
});
});
#1
You can wait for the user to be loaded via an autorun:
您可以等待通过自动运行加载用户:
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()
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:
我们还利用coffeescript的存在运算符来安全地提取名称值。在javascript中,此解决方案看起来像这样:
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();
}
});
});