Use separate message collections for each thread to facilitate lookup and lazy loading

This commit is contained in:
lilia 2014-07-22 04:14:33 -10:00
parent d6d17eaf19
commit ebf1b3352f
3 changed files with 18 additions and 7 deletions

View File

@ -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',

View File

@ -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;
},
});

View File

@ -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();
},