如何在Meteor中停止并重新启动收集观察者?

Mik*_*raf 8 javascript meteor

我希望能够停止并重新启动Meteor中我的集合上的观察者.

想象一下,我有以下观察者:

 // Imagine some collection of Blog posts "Posts"
  Posts.find().observe({
    changed: notifySubscribedUsers
  });

 // function notifySubscribedUsers() { ... }  
 //    is some function that will email everyone saying some post was updated
Run Code Online (Sandbox Code Playgroud)

现在想象一下我想要更新很多帖子,但我不希望调用观察者.如何访问观察者,停止/暂停它们,然后重新启动它们(在db作业完成后)?

TIA

Aks*_*hat 15

观察者返回一个句柄:

var handle = Posts.find().observe({
    changed: notifySubscribedUsers
});
Run Code Online (Sandbox Code Playgroud)

然后你可以用以下方法阻止它:

handle.stop()
Run Code Online (Sandbox Code Playgroud)

传统意义上的"暂停"它是不可能的,如果你想暂停它,你可以忽略它给你的数据.

要用一个整齐的包装方法做到这一点,你可以做类似的事情:

var handle;

var start = function() {
   if(handle) handle.stop();
   var handle = Posts.find().observe({
    changed: notifySubscribedUsers
   });
}

var stop = function() { if(handle) handle.stop }
Run Code Online (Sandbox Code Playgroud)

或者把它放在一个集合上:

// posts.js collection file
Posts.startObservers = function startObservers() {
  Posts.observer = Posts.find().observe({
    change: notifySubscribedUsers // or some other function
  });
};

Posts.stopObservers = function stopObservers() {
  if(Posts.observer) {
    Posts.observer.stop(); // Call the stop
  }
};


// Trigger Somewhere else in the code
Posts.stopObservers();
MyTool.doWorkOnPosts(); // Some contrived work on the Posts collection
Posts.startObservers();
Run Code Online (Sandbox Code Playgroud)

  • 您必须重新运行posts observer才能重新创建查询.您可以将其包装在自己的方法中,以使其更容易 (2认同)