Reputation: 43
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).
Current implementation uses set interval to keep checking for db changes:
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.
So can you guys think of a better CLEAN solution without using setInterval ?
Upvotes: 0
Views: 134
Reputation: 64312
You can just use an autorun inside of your onRendered
callback:
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
.
Upvotes: 2