From ebf1b3352f0d574c2a3e7259419185ade1b841a4 Mon Sep 17 00:00:00 2001 From: lilia Date: Tue, 22 Jul 2014 04:14:33 -1000 Subject: [PATCH] Use separate message collections for each thread to facilitate lookup and lazy loading --- js/models/messages.js | 16 ++++++++++++---- js/models/threads.js | 4 +++- js/views/conversations/show.js | 5 +++-- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/js/models/messages.js b/js/models/messages.js index c3a5ea981..92d3f7b74 100644 --- a/js/models/messages.js +++ b/js/models/messages.js @@ -15,6 +15,14 @@ var Whisper = Whisper || {}; } }); + Whisper.MessageCollection = Backbone.Collection.extend({ + model: Message, + comparator: 'timestamp', + initialize: function(models, options) { + this.localStorage = new Backbone.LocalStorage("Messages-" + options.threadId); + } + }); + Whisper.Messages = new (Backbone.Collection.extend({ localStorage: new Backbone.LocalStorage("Messages"), model: Message, @@ -27,7 +35,7 @@ var Whisper = Whisper || {}; attachments[i] = "data:" + decrypted.message.attachments[i].contentType + ";base64," + btoa(getString(decrypted.message.attachments[i].decrypted)); var thread = Whisper.Threads.findOrCreateForIncomingMessage(decrypted); - var m = Whisper.Messages.add({ + var m = thread.messages().add({ person: decrypted.pushMessage.source, threadId: thread.id, body: decrypted.message.body, @@ -38,15 +46,15 @@ var Whisper = Whisper || {}; m.save(); if (decrypted.message.timestamp > thread.get('timestamp')) { - thread.set('timestamp', decrypted.message.timestamp); - thread.set('unreadCount', thread.get('unreadCount') + 1); + thread.set({timestamp: decrypted.message.timestamp}); + thread.set({unreadCount: thread.get('unreadCount') + 1}); thread.save(); } return m; }, addOutgoingMessage: function(message, thread) { - var m = Whisper.Messages.add({ + var m = thread.messages().add({ threadId: thread.id, body: message, type: 'outgoing', diff --git a/js/models/threads.js b/js/models/threads.js index 75c8aa1b8..bf5add901 100644 --- a/js/models/threads.js +++ b/js/models/threads.js @@ -36,7 +36,9 @@ var Whisper = Whisper || {}; }, messages: function() { - return Whisper.Messages.where({threadId: this.id}); + var messages = new Whisper.MessageCollection([], {threadId: this.id}); + messages.fetch(); + return messages; }, }); diff --git a/js/views/conversations/show.js b/js/views/conversations/show.js index 13d6a418f..e6785c057 100644 --- a/js/views/conversations/show.js +++ b/js/views/conversations/show.js @@ -12,7 +12,8 @@ var Whisper = Whisper || {}; }, destroy: function() { - _.each(this.model.messages(), function(message) { message.destroy(); }); + + this.model.messages().each(function(message) { message.destroy(); }); this.model.destroy(); } }); @@ -103,7 +104,7 @@ var Whisper = Whisper || {}; }, addAllMessages: function () { - _.each(this.model.messages(), this.addMessage, this); + this.model.messages().each(this.addMessage, this); this.render(); },