【问题标题】:Meteor observe changes added callback流星观察更改添加回调
【发布时间】:2015-05-11 23:53:18
【问题描述】:

@DavidWeldon 我尝试了您的代码 (Meteor observe changes added callback on server fires on all item),非常好,谢谢!

但是我想听听您的建议:我将它用于桌面通知:当我收到一个通知时,有一个控制台日志(好的),但是当我收到另一个通知(总数:2)时,有两个控制台日志(我只想要一个控制台日志,因为只有 +1 通知)

这是我的代码:

if (Notification.permission !== "granted")
Notification.requestPermission();

var query = Notifications.find({userId: Meteor.userId(), read: false});
(function() {
  var initializing = true;
  query.observeChanges({
    added: function(id, notification) {
      if (!initializing) {
        console.log(notification);
      }
    }
  });
  initializing = false;
})();

感谢您的帮助! :)

【问题讨论】:

    标签: meteor


    【解决方案1】:

    你可以在那里使用另一个标志吗?

    if (Notification.permission !== "granted")
    Notification.requestPermission();
    
    var query = Notifications.find({userId: Meteor.userId(), read: false});
    (function() {
      var initializing = true;
      var firstNotif = true;
      query.observeChanges({
        added: function(id, notification) {
          if (!initializing && firstNotif) {
            firstNotif = false;
            console.log(notification);
          }
        }
      });
      initializing = false;
    })();
    

    【讨论】:

    • 使用该解决方案没有显示控制台日志
    • 是的,我的错,对不起,我修正了我的答案。
    【解决方案2】:

    我终于找到了答案,在发现流星中探索这个帖子:https://www.discovermeteor.com/blog/template-level-subscriptions/

    (在我的问题中,我在 Template.notifications.helpers 工作)

    这是我的新代码:

    Template.notifications.onCreated(function () {
    
      if (Notification.permission !== "granted")
      Notification.requestPermission();
    
      var instance = this;
      instance.autorun(function () {
        var query = Notifications.find({userId: Meteor.userId(), read: false});
        query.observeChanges({
          added: function(id, notification) {
            var notification = new Notification('Notification', {
              icon: '',
              body: "You got a new notification !"
            });
          }
        });
      });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 2015-06-24
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多