Implement infinite scrolling message lists

Only load the most recent messages when initially rendering a
conversation. Scrolling to the top of a message list loads older
messages.

This required some slight refactoring of how we insert message elements
into the dom. If the message is added to the end of the collection,
append it at the end. Otherwise, assume it is an older message and
prepend it.

When adding elements to the top, reset the scrollPosition to its
previous distance from scrollHeight. This keeps the current set of
elements fixed in the viewport.

// FREEBIE
This commit is contained in:
lilia 2015-11-10 16:03:19 -08:00
parent abf402b8c5
commit 2861fa26a7
7 changed files with 75 additions and 33 deletions

View file

@ -10,14 +10,15 @@
className: 'message-list',
itemView: Whisper.MessageView,
events: {
'add': 'onAdd',
'update *': 'scrollToBottom',
'scroll': 'measureScrollPosition',
'update *': 'scrollToBottomIfNeeded',
'scroll': 'onScroll',
'reset-scroll': 'resetScrollPosition'
},
onAdd: function() {
this.$el.removeClass('loading');
this.scrollToBottom();
onScroll: function() {
this.measureScrollPosition();
if (this.$el.scrollTop() === 0) {
this.$el.trigger('loadMore');
}
},
measureScrollPosition: function() {
if (this.el.scrollHeight === 0) { // hidden
@ -47,6 +48,22 @@
addAll: function() {
Whisper.ListView.prototype.addAll.apply(this, arguments); // super()
this.scrollToBottom();
}
},
addOne: function(model) {
if (this.itemView) {
var view = new this.itemView({model: model}).render();
if (this.collection.indexOf(model) === this.collection.length - 1) {
// add to the bottom.
this.$el.append(view.el);
this.scrollToBottom();
} else {
// add to the top.
var offset = this.el.scrollHeight - this.$el.scrollTop();
this.$el.prepend(view.el);
this.$el.scrollTop(this.el.scrollHeight - offset);
}
}
this.$el.removeClass('loading');
},
});
})();