Skip to content

Instantly share code, notes, and snippets.

@ehynds
Created October 6, 2011 20:52
Show Gist options
  • Save ehynds/1268643 to your computer and use it in GitHub Desktop.
Save ehynds/1268643 to your computer and use it in GitHub Desktop.
backbone lazy loading nested collections w/ caching...
// inbox view
app.views.Inbox = Backbone.View.extend({
events: {
"click .view-message": "view"
},
view: function(event) {
var id = $(event.target).data("message-id");
var model = this.collection.get(id);
message.render(model);
// .. or do pub/sub, whatever.
}
});
var inbox = new app.views.Inbox({
collection: messages
});
// Mailbox model
app.models.Mailbox = Backbone.Model.extend({
initialize: function() {
this.files = new app.collections.Messages();
this.files.url = "/mailbox/" + this.id + "/messages";
// clear the cache when this model changes, so the
// next time the mailbox is loaded it receives
// fresh data.
this.bind("change", function(){
this.files.clearCache();
});
},
});
// individual message view
app.views.Message = Backbone.View.extend({
render: function( model ) {
$.when(this.getTemplate(), model.messages.get()).then(_.bind(function(template, messages){
this.el.html(template({
messages: messages
}));
}, this));
}
});
var message = new app.views.Message;
// Each mailbox model receives a messages collection
app.collections.Messages = Backbone.Collection.extend({
model: app.models.Message,
get: function() {
return this.cache || (this.cache = this.fetch().pipe(function(data){
return data;
}));
},
clearCache: function() {
this.cache = null;
}
});
var messages = new app.collections.Messages;
@ehynds
Copy link
Author

ehynds commented Oct 6, 2011

There's probably a better way to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment