【问题标题】:Meteor run a function when a mongo collection gets updated当 mongo 集合更新时,Meteor 运行一个函数
【发布时间】:2015-04-13 12:15:00
【问题描述】:

我正在尝试使用 Meteor 做一个简单的原型(我对 Meteor 很陌生)。

我在 isClient 块中有以下内容

    Template.imageList.helpers({
    images: function() {
        return Images.find({});
  },
}
);

然后出于快速演示的目的,我将使用流星 mongo 和以下内容插入数据

db.images.insert({ imgSrc: "http://mysite/img1.png", createdAt: new Date() })

这可行,我可以看到 ui 上反映的更改,但是当发生这种情况时,我还需要运行客户端 javascript 函数。我一直在尝试诸如 pub/sub 和 Tracker 之类的东西,但什么都做不了。

任何指导都会很棒。

【问题讨论】:

  • 'images' 助手中的代码默认是响应式的,所以当集合发布更新时它会改变。您可以在返回之前运行脚本,但这可能会在每次更改时触发多次。

标签: meteor


【解决方案1】:

使用meteor-collections-hooks 是完成此任务的更简单方法。

meteor add matb33:collection-hooks

例如。

Images = new Mongo.Collection('Images')
example = function(){
  console.log("updated")
}
if (Meteor.isClient) {
  Images.before.update(function(userId, doc, fieldNames, modifier, options){
     example();
  })
}

example() 函数将在每次更新 Images collection 时运行。

【讨论】:

  • 这仅在集合从 Meteor 端更新时才有效。如果从外部服务获取更新,这不起作用
  • @ThaiTran 您可以扩展上述内容吗?我遇到了一个问题,并试图弄清楚数据来自 webhook 的事实是否是问题所在。尽管如此,所有数据仍会通过集合进行更新。
  • @Rockafella 作为 Meteor 1.3 你可能不需要 collections:hooks 包,你可以改为子类化你的 collection,看看这个class ListsCollection extends Mongo.Collection { // ... remove(selector, callback) { Package.todos.Todos.remove({listId: selector}); return super.remove(selector, callback); } }
  • 感谢@Ethaan,我会研究这种方法!这次我在服务器上使用了 collection:hooks,而在客户端上只使用了 .observe(我最初的问题是 collection:hooks 在客户端没有触发)
  • 我认为观察者在客户端上使用起来非常繁重,您可以改为使用不同的解决方案,但如果它适合您,我想没问题@Rockafella
【解决方案2】:

使用observeChanges

Images.find().observeChanges({
   added: function (id, fields) {
       runFunction();
   },
   changed: function (id, fields) {
       runFunction();
   },
   removed: function (id) {
       runFunction();
  }
});

更多信息请看这里:http://docs.meteor.com/#/full/observe_changes

【讨论】:

  • 虽然我不知道这是否是最佳答案,但这与我为解决问题所做的工作非常接近,但我确实将其包装在 Meteor.autosubscribe(...) 中。跨度>
【解决方案3】:

在客户端的模板助手上运行函数,例如:

Template.imageList.helpers({
  images: function() {
    imgs = Images.find({});
    yourFunction();
    return images;
  }
});

或者使用Tracker.autorun包装器:

Tracker.autorun(
   Images.find({});
   yourFunction();
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 2014-07-20
    相关资源
    最近更新 更多