Permalink
Browse files

Load previous messages when page is scrolled to top

  • Loading branch information...
1 parent cbfc202 commit 13332c30a656a74b6ce4e73a63d3550b79fb838b @edzhelyov committed Sep 29, 2011
Showing with 47 additions and 1 deletion.
  1. +3 −1 app/controllers/chat/messages_controller.rb
  2. +44 −0 public/javascripts/uw.logs.js
@@ -19,8 +19,10 @@ def index
@since, params[:last_id].to_i])
else
total_messages = @messages.count
+ limit = (params[:limit] || 200).to_i
+ offset = (params[:offset] || 0).to_i * limit
- @messages = @messages.limit(params[:limit] || 200) unless params[:full_log]
+ @messages = @messages.limit(limit).offset(offset) unless params[:full_log]
@more_messages = total_messages > @messages.length
end
@@ -10,10 +10,12 @@ UW.Logs.init = function(options){
this.topic = options.topic;
this.refreshInterval = options.refreshInterval || 60 * 60 * 1000;
this.startedTime = new Date;
+ this.offset = 0;
$.scrollTo('#bottom', { axis: 'y' });
setTimeout(this.loadMessages, 3000);
+ $(document).bind('scroll', this.loadPreviousMessages);
}
UW.Logs.loadMessages = function(){
@@ -92,3 +94,45 @@ UW.Logs.displayStoppedRefreshMessage = function(){
$.scrollTo('#flash', { axis: 'y' });
}
+
+UW.Logs.loadPreviousMessages = function(){
+ var firstMessagePosition = $('table.messages tr.date:first').position().top,
+ doc = $(document);
+
+ if (firstMessagePosition < doc.scrollTop()) return;
+
+ doc.unbind('scroll', UW.Logs.loadPreviousMessages);
+
+ UW.Logs.offset += 1;
+ var currentView = doc.height() - doc.scrollTop();
+
+ $.ajax({
+ url: UW.Logs.url,
+ dataType: 'json',
+ data: {
+ channel: UW.Logs.channel,
+ topic: UW.Logs.topic,
+ offset: UW.Logs.offset
+ },
+ success: function(data){
+ if(!(data instanceof Array)) {
+ UW.Logs.loadMessagesError();
+ return;
+ }
+
+ if (data.length > 0) {
+ var container = $('<div></div>');
+
+ for (var x = 0; x < data.length; x++) {
+ container.append(data[x].html);
+ }
+
+ $('table.messages tr.date:first').replaceWith(container.html());
+ doc.scrollTop(doc.height() - currentView);
+
+ doc.bind('scroll', UW.Logs.loadPreviousMessages);
+ }
+ },
+ error: UW.Logs.loadMessagesError
+ });
+}

0 comments on commit 13332c3

Please sign in to comment.