Collection 即使我使用了 waitOn,也没有按时呈现?
Collection not rendered on time even though I'm using waitOn?
这是代码:
Meteor.publish('singleDocument', function(documentId) {
return Documents.find(documentId);
});
this.route("documentPage", {
path: "/documents/:_id",
waitOn: function() {
return Meteor.subscribe("singleDocument", this.params._id);
},
data: function() {
return Documents.findOne(this.params._id);
}
});
Template.documentPage.rendered = function() {
Tracker.autorun(function() {
console.log(this.content);
});
};
如您所见,我已准备好一切,正在等待 collection 和 waitOn
。但是 console.log(this.content);
仍然返回 undefined
就好像 collection 还没有加载。
可能是什么问题?
autorun 中的 this
不引用用于呈现模板的数据上下文。在渲染函数中,在自动运行函数之外(你根本不需要使用自动运行),你可以使用 this.data
来引用用于渲染模板的数据上下文,因此请尝试以下操作:
Template.documentPage.rendered = function() {
console.log(this.data);
};
根据下面的评论更新:
您应该能够使用 Template.currentData 来监听数据上下文中的变化:
Template.documentPage.rendered = function() {
Tracker.autorun(function(){
console.log(Template.currentData())
})
};
这是代码:
Meteor.publish('singleDocument', function(documentId) {
return Documents.find(documentId);
});
this.route("documentPage", {
path: "/documents/:_id",
waitOn: function() {
return Meteor.subscribe("singleDocument", this.params._id);
},
data: function() {
return Documents.findOne(this.params._id);
}
});
Template.documentPage.rendered = function() {
Tracker.autorun(function() {
console.log(this.content);
});
};
如您所见,我已准备好一切,正在等待 collection 和 waitOn
。但是 console.log(this.content);
仍然返回 undefined
就好像 collection 还没有加载。
可能是什么问题?
this
不引用用于呈现模板的数据上下文。在渲染函数中,在自动运行函数之外(你根本不需要使用自动运行),你可以使用 this.data
来引用用于渲染模板的数据上下文,因此请尝试以下操作:
Template.documentPage.rendered = function() {
console.log(this.data);
};
根据下面的评论更新:
您应该能够使用 Template.currentData 来监听数据上下文中的变化:
Template.documentPage.rendered = function() {
Tracker.autorun(function(){
console.log(Template.currentData())
})
};