gpt4 book ai didi

javascript - Meteor:每次集合更改时如何触发命令?

转载 作者:行者123 更新时间:2023-11-28 08:27:06 26 4
gpt4 key购买 nike

我有一个显示评论的 meteor 模板。我已经设置了一个响应式(Reactive)模板助手,当用户添加回复时它会返回回复。我想在回复数量发生变化时触发一个函数(即当任何用户向当前讨论添加新回复时),但我不确定执行此操作的最佳方法是什么。

目前,我将此设置作为模板助手的一部分,但这似乎非常脆弱。

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

时,我也在控制台中收到此错误

最佳答案

根据您的用例,您可以在 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');
}
});
});

或者您可以简单地执行此操作,只要您的 session 变量发生更改,就会运行该函数,以更适合您的用例为准:

Deps.autorun(function () {
var discussionId = Session.get("openedDiscussion");
if (discussionId) {
foobar();
console.log('There are is a new reply from someone else');
}
});

关于javascript - Meteor:每次集合更改时如何触发命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22277850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com