我有一个显示评论的流星模板。我已经设置了一个反应模板助手,当用户添加回复时,它会返回回复。我希望在回复数量发生变化时触发一个函数 - 当任何用户向当前讨论添加新回复时),但我不确定最好的方法是什么。
目前,我将此设置作为模板助手的一部分,但这看起来非常脆弱。
Template.comments.helpers({
replies: function() {
var discussionId = Session.get("openedDiscussion");
var replies = Replies.find({discussionId: discussionId});
// I want this function to run every time the # of replies changes.
foobar();
console.log('There are is a new reply from someone else');
return replies;
}
});
我也尝试过使用Deps.autorun,但无法弄清楚如何正确使用Session对象。我也不确定将它放在我的Meteor项目中的位置:
Deps.autorun(function () {
var discussionId = Session.get("openedDiscussion");
var replies = Replies.find({discussionId: discussionId});
// I want this function to run every time the # of replies changes.
foobar();
console.log('There are is a new reply from someone else');
});
当我尝试Uncaught ReferenceError: Replies is not defined
答案 0 :(得分:0)
根据您的使用案例,您可以订阅Deps.run
中的集合,以便每次收集更改时重新运行该函数:
Deps.autorun(function () {
Meteor.subscribe("replies", function() {
var discussionId = Session.get("openedDiscussion"); // get the newly added item here depending on your business case
if (discussionId) {
foobar();
console.log('There are is a new reply from someone else');
}
});
});
或者您只需执行此操作即可在会话变量发生更改时运行该函数,以适合您的用例为准:
Deps.autorun(function () {
var discussionId = Session.get("openedDiscussion");
if (discussionId) {
foobar();
console.log('There are is a new reply from someone else');
}
});