流星 - 观察自动运行功能内未运行

Meteor - observe not running inside autorun function

本文关键字:运行 功能 观察 流星      更新时间:2023-09-26

为什么当观察程序内的查询更改时不触发通知?当我将此代码放入帮助程序中时,它可以工作,但仅适用于该帮助程序模板。

Tracker.autorun(function () {
  Meteor.subscribe('theNotificationStatus');
  Meteor.subscribe('theNotificationSubscriptions');
  var currentUserID = Meteor.userId();
  var usersEventIds =  Subscriptions.find({userID: currentUserID}, {"eventID": 1});
  var userCategorys = Subscriptions.find({userID: currentUserID}, {"category": 1});
  var arrayEvents = [];
  var arrayCategory =[];
  usersEventIds.forEach(function (collection) {
    arrayEvents.push(collection.eventID);
  });
  userCategorys.forEach(function (collection) {
    arrayCategory.push(collection.category);
  });

  //All of the status's the user should be notified for based on what eventID and categories he/she is subscribed to.
  var query = Status.find({ $and: [ { eventID: { $in: arrayEvents  } } , { category: { $in: arrayCategory } }, { createdBy: { $ne: currentUserID } } ] }, {sort: {date: -1} } );
  var handle = query.observe({
    added: function (id, fields) {
      sAlert.success('New Notifications', {timeout: '6000'});
    },
  });
  // After five seconds, stop keeping the count.
  setTimeout(function () {handle.stop();}, 5000);
});

如果你使用 React,当你把它放在Template.someTemplate.onCreatedcomponentWillMount中时,你会得到什么日志?

Meteor.subscribe('theNotificationStatus');
Meteor.subscribe('theNotificationSubscriptions'); 
Tracker.autorun(function () {
  var currentUserID = Meteor.userId();
  var subscriptions =  Subscriptions.find(
    {userID: currentUserID},
    {fields: {eventID: 1, category: 1}}
  );
  console.log('currently, there are', subscriptions.count(), 'subscriptions loaded');
  var arrayEvents = [];
  var arrayCategory =[];
  subscriptions.forEach(function (subscription) {
    arrayEvents.push(collection.eventID);
    arrayCategory.push(collection.category);
  });

  //All of the status's the user should be notified for based on what eventID and categories he/she is subscribed to.
  var query = Status.find({
    eventID: { $in: arrayEvents },
    category: { $in: arrayCategory },
    createdBy: { $ne: currentUserID },
  });
  console.log('currently, there are', query.count(), 'status loaded');
  var handle = query.observe({
    added: function (status) {
      console.log('new status', status);
    },
  });
});