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

pull/749/head
lilia 11 years ago
parent d6d17eaf19
commit ebf1b3352f

@ -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({ Whisper.Messages = new (Backbone.Collection.extend({
localStorage: new Backbone.LocalStorage("Messages"), localStorage: new Backbone.LocalStorage("Messages"),
model: Message, 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)); attachments[i] = "data:" + decrypted.message.attachments[i].contentType + ";base64," + btoa(getString(decrypted.message.attachments[i].decrypted));
var thread = Whisper.Threads.findOrCreateForIncomingMessage(decrypted); var thread = Whisper.Threads.findOrCreateForIncomingMessage(decrypted);
var m = Whisper.Messages.add({ var m = thread.messages().add({
person: decrypted.pushMessage.source, person: decrypted.pushMessage.source,
threadId: thread.id, threadId: thread.id,
body: decrypted.message.body, body: decrypted.message.body,
@ -38,15 +46,15 @@ var Whisper = Whisper || {};
m.save(); m.save();
if (decrypted.message.timestamp > thread.get('timestamp')) { if (decrypted.message.timestamp > thread.get('timestamp')) {
thread.set('timestamp', decrypted.message.timestamp); thread.set({timestamp: decrypted.message.timestamp});
thread.set('unreadCount', thread.get('unreadCount') + 1); thread.set({unreadCount: thread.get('unreadCount') + 1});
thread.save(); thread.save();
} }
return m; return m;
}, },
addOutgoingMessage: function(message, thread) { addOutgoingMessage: function(message, thread) {
var m = Whisper.Messages.add({ var m = thread.messages().add({
threadId: thread.id, threadId: thread.id,
body: message, body: message,
type: 'outgoing', type: 'outgoing',

@ -36,7 +36,9 @@ var Whisper = Whisper || {};
}, },
messages: function() { messages: function() {
return Whisper.Messages.where({threadId: this.id}); var messages = new Whisper.MessageCollection([], {threadId: this.id});
messages.fetch();
return messages;
}, },
}); });

@ -12,7 +12,8 @@ var Whisper = Whisper || {};
}, },
destroy: function() { destroy: function() {
_.each(this.model.messages(), function(message) { message.destroy(); });
this.model.messages().each(function(message) { message.destroy(); });
this.model.destroy(); this.model.destroy();
} }
}); });
@ -103,7 +104,7 @@ var Whisper = Whisper || {};
}, },
addAllMessages: function () { addAllMessages: function () {
_.each(this.model.messages(), this.addMessage, this); this.model.messages().each(this.addMessage, this);
this.render(); this.render();
}, },

Loading…
Cancel
Save