Created
October 6, 2011 20:52
-
-
Save ehynds/1268643 to your computer and use it in GitHub Desktop.
backbone lazy loading nested collections w/ caching...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}); | |
}, | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's probably a better way to do this.