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
@mxriverlynn
Copy link
Author

Not entirely sure I understand... are you trying to lazy-load the subFoos when you need them?

FooModel = Backbone.Model.extend({

  getSubFoos: function(){
    if (!this.subFoos){
      this.subFoos = new FooCollection({parentId: this.id});
      subFoos.fetch();
    }
    return this.subFoos;
  };

});

FooCollection = Backbone.Collection.extend({

  initialize: function(data, options){
    this.parentId = options.parentId;
  }

  url: function(){
    var url;
    if (this.parentId){
      url = "/foo/" + this.parentId + "/SubFoos";
    } else {
      url = "/SomethingElse/WithNo/ParentId";
    }
    return url;
  }

});

Something like that should work, I think.

@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