替代setInterval()数据库检查 - > Meteor.js

时间:2021-07-14 17:28:04

The idea is pretty simple I need to do scroll-down message feed when number of records is changed or when new message is inserted into doc (same thing).

这个想法非常简单我需要在更改记录数量或将新消息插入doc(同样的事情)时进行向下滚动消息。

Current implementation uses set interval to keep checking for db changes:

当前实现使用set interval来继续检查db更改:

Template['messenger'].onCreated(function(){
    $(function(){
        Template['messenger'].methods.scrollOnNewMessages().start();
    })
});

Template['messenger'].methods = {

    scrollOnNewMessages : function () {
        return {
            oldCount : 0,

            start : function () {
                this.oldCount = Messages.find().count();
                setInterval(this.funcToRepeat, 400);
            },

            funcToRepeat : function () {
                var newCount = Messages.find().count();
                var updated = this.oldCount !== newCount;
                if(updated){
                    this.oldCount = newCount;
                    Template['messenger'].methods.scrollDown();
                }
            }

        }
    },

    scrollDown: function () {
        var height = $(".messageEntry").outerHeight() + 3;
        var scrollLength = $('.messageEntry').length * height - $("#messageFeed").height();
        $('#messageFeed').animate({scrollTop:scrollLength}, 400, 'swing');
    },
}

This works pretty well, but I hate the idea of using setInterval(). Tried doing this with Template.my_template.onRendered but this will execute a function on every template that was rendered that means if I have 50 messages rendered on startup it will auto-scroll 50 times without much purpose.

这很好用,但我讨厌使用setInterval()的想法。尝试使用Template.my_template.onRendered执行此操作,但这将在每个呈现的模板上执行一个函数,这意味着如果我在启动时呈现50条消息,它将自动滚动50次而没有太多用途。

So can you guys think of a better CLEAN solution without using setInterval ?

那么你们可以在不使用setInterval的情况下考虑更好的CLEAN解决方案吗?

1 个解决方案

#1


2  

You can just use an autorun inside of your onRendered callback:

您可以在onRendered回调中使用自动运行:

Template.messenger.onRendered(function() {
  this.autorun(function() {
    if (Messages.find().count())
      Template.messenger.methods.scrollDown();
  });
});

Because the count is reactive, the autorun will fire every time it changes. Try adding that and removing scrollOnNewMessages and its reference in onCreated.

由于计数是被动的,因此每次更改时都会触发自动运行。尝试添加并删除scrollOnNewMessages及其在onCreated中的引用。

#1


2  

You can just use an autorun inside of your onRendered callback:

您可以在onRendered回调中使用自动运行:

Template.messenger.onRendered(function() {
  this.autorun(function() {
    if (Messages.find().count())
      Template.messenger.methods.scrollDown();
  });
});

Because the count is reactive, the autorun will fire every time it changes. Try adding that and removing scrollOnNewMessages and its reference in onCreated.

由于计数是被动的,因此每次更改时都会触发自动运行。尝试添加并删除scrollOnNewMessages及其在onCreated中的引用。