javascript - 如何在 meteor 页面加载后调用函数

标签 javascript jquery angularjs meteor angular-meteor

我使用cursor.observechanges来查看mongo中是否插入了任何新记录,并在插入新记录时发出通知,它运行良好。但这里的问题是当我的应用程序第一次加载时,我收到这些通知警报,因为它观察到这些变化。当我点击下一页时也是如此。

cursor.observeChanges({
  added: function(id, object) {
    Notification.error('NEW Record',object);
    var audio = new Audio('audio.mp3');
    audio.play();
  }
});

所以我只需要在页面加载后调用这个函数。我尝试使用

Template.foo.onRendered(function () {
  cursor.observeChanges({
    added: function(id, object) {
      Notification.error('NEW Record',object);
      var audio = new Audio('audio.mp3');
      audio.play();
    }
  });
});

但它在我的情况下不起作用。有没有其他方法可以做到这一点。或者如果可能的话,我们如何设置 5 秒的时间并在该时间间隔后调用上述函数? 任何帮助将不胜感激。谢谢!

最佳答案

根据docs Template#onRendered:

Register a function to be called when an instance of this template is inserted into the DOM.

尝试将代码包装在 Meteor.defer 中:

Template.foo.onRendered(function() {
  Meteor.defer(function() {
    cursor.observeChanges({
      added: function(id, object) {
        Notification.error('NEW Record',object);
        var audio = new Audio('audio.mp3');
        audio.play();
      }
    });
  })
});

如果没有帮助,请尝试将其包装在Meteor.setTimeout中:

Template.foo.onRendered(function() {
  Meteor.setTimeout(function() {
    cursor.observeChanges({
      added: function(id, object) {
        Notification.error('NEW Record',object);
        var audio = new Audio('audio.mp3');
        audio.play();
      }
    });
  }, 5000)
});

关于javascript - 如何在 meteor 页面加载后调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42501726/

相关文章:

javascript - 如何判断剑道 UI 网格中的 destroy 命令销毁了什么?

javascript - JQuery 覆盖图像 onclick 无需预加载

location - AngularJS - 更新 $route 参数的最佳方式

javascript - 提取字符串的中间或最后部分

javascript - 使用 vue-i18n 翻译 Vue 组件属性的默认值

javascript - 提取包含文本节点的 HTML,而不对其进行编码

javascript - 使用 JQuery AJAX 将值传递给 PHP 不起作用,数组困惑

javascript - 导致 infdig 的过滤器/函数

javascript - ES6 : this is undefined despite using bind()

javascript - 如何在弹出窗口中添加链接