Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created September 5, 2012 19:58
Show Gist options
  • Save mxriverlynn/3643596 to your computer and use it in GitHub Desktop.
Save mxriverlynn/3643596 to your computer and use it in GitHub Desktop.
a very basic nested model structure
var data = {
name: "foo",
subFoos: [
{name: "bar"},
{name: "baz"},
]
};
FooModel = Backbone.Model.extend({
initialize: function(){
this.setupSubFoos();
},
setupSubFoos: function(){
var subFoos = this.get("subFoos");
this.unset("subFoos", {silent: true});
this.subFoos = new FooCollection(subFoos);
}
});
FooCollection: Backbone.Model.extend({
model: FooModel
});
// i extracted the "setupSubFoos" in to a function called `getChildren` so that i could do something like:
this.subFoos = this.getChildren("subFoos");
// and then i could put that one liner in the initializer of the model, directly
@gilesbowkett
Copy link

yes on lazy-loading the sub foos.

I'm thinking more something like

class SubFoos extends Backbone.Collection
  url: "http://website.com/whatever"
  initialize: ->
    @url = "http://website.com/foos/#{@parent_id}/subfoos"
class BigPapaFoo extends Backbone.Model
  @getSubFoos: ->
    @subFoos = new SubFoos(parent_id: 12345)
    @subFoos.fetch()

and then in the view, when you drill down from viewing a collection of foos to a detail view where you see just one foo and its associated subfoos:

@model.getSubFoos()

@mxriverlynn
Copy link
Author

yeah, that looks a bit nicer in implementation

@gilesbowkett
Copy link

sweet! much thanks.

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