【问题标题】:Meteor: How do I trigger a command every time a collection changes?Meteor:如何在每次集合更改时触发命令?
【发布时间】:2014-03-19 19:29:41
【问题描述】:

我有一个显示 cmets 的流星模板。我设置了一个响应式模板助手,当用户添加回复时,它会返回回复。我想在回复数量发生变化时触发一个函数——当任何用户向当前讨论添加新回复时),但我不确定最好的方法是什么。

目前,我将此设置作为模板帮助程序的一部分,但这似乎真的很脆弱。

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 时,我也在控制台中收到此错误

【问题讨论】:

  • 该文件中是否有回复?您是否将Replies 设为全局变量(没有var 关键字?)。你确定你只在客户端运行它吗?

标签: javascript meteor


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    相关资源
    最近更新 更多