在嵌套函数内部时,停止返回函数是否​​仍然停止?

Are stop-returning functions still stopped when inside nested functions?

In addition, the following functions which return an object with a stop method, if called from a reactive computation, are stopped when the computation is rerun or stopped:

Tracker.autorun (nested) Meteor.subscribe observe() and observeChanges() on cursors

这意味着观察到此为止:

Tracker.autorun ->
  cursor.observe()

但是这里呢?

Tracker.autorun ->
  Tracker.nonReactive ->
    cursor.observe()

当在反应式计算中创建 MiniMongo 反应式句柄(find()observe() 等)时,MiniMongo 将检测到它并附加一个侦听器计算的 onInvalidate 将在计算无效(或停止)时停止句柄。

这是否直接在autorun回调中完成并不重要 或者在从回调它调用的函数中,只要它是同步完成的(即,在同一计算的上下文中)。

有一个值得注意的例外:非反应性回调。

Tracker.nonreactive 回调在非反应性上下文中触发,因此 current computation is set to null and Tracker.active is set to false. Under those conditions, MiniMongo will not attach the aforementioned listener 和更改观察器不会自动停止。

不过您可以手动停止它:

const MyCollection = new Mongo.Collection(null);
const cursor1 = MyCollection.find({foo: 'bar'});
const cursor2 = MyCollection.find({foo: 'baz'});

let observeCallback = {
  added(doc) {
    console.log('added', doc);
  }
};


let handle = Tracker.autorun(function(c) { // c is the computation object
  cursor1.observe(observeCallback); // will be automatically stopped

  Tracker.nonreactive(function() {
    let observer = cursor2.observe(observeCallback);
    c.onStop(function() {
      observer.stop(); // explicitly stops the observer
    })

  });

});

MyCollection.insert({foo: 'bar'});
MyCollection.insert({foo: 'baz'});

handle.stop();