3

I'm having an issue wrapping my head around relational models in Backbone. I've just started using it and I'm tasked with a fairly large application.

The main issue I'm having is that I have a model that should contain a collection.

This is what I have to work with:

  • modelA
    • id: _id
    • url: api/model/:modelA_id
    • nested:
      • url: api/:modelA_id/nest

I think I'm making it a bigger deal than I need to, but I just can't seem to wrap my head around how to set this up.

Any help will be most appreciated.

MikeD
  • 123
  • 4
  • Are you using the `backbone-relational` plugin for this? Just trying to clarify. Might not hurt to show your actual code, too. – Rob Hruska Mar 20 '12 at 15:30
  • Yes I'm using that plugin. At the moment I have just the base code that is in the docs to have relations set up. However, I'm not sure how to pull modelA_id into the url of the nested collection. I think that is my first issue to tackle. – MikeD Mar 20 '12 at 15:36

1 Answers1

9

The biggest thing to wrap your head around with Backbone is how to properly use events to deal with basically everything in the app. The other big thing to understand is that there are probably 5 different ways to attack a problem, where none of them are better/worse than the other.

Given that loose structure you've provided, I would do something like:

var YourApp = {
   Models : {}
   Collections : {}
   Views : {}
};

YourApp.Models.First = Backbone.Model.extend({
  initialize : function(){
      var nestedCollection;
      this.url = 'api/model/' + this.id;
      nestedCollection = new Backbone.Collection({
        url : this.url + '/nest'
      });
      this.set('nested', nestedCollection);
    }
});

new YourApp.Models.First({
  id : 23
});
tgriesser
  • 2,808
  • 1
  • 22
  • 22
  • Agreed, there's nothing saying an one of your models attributes can't be a backbone collection. – ryanmarc Mar 21 '12 at 05:49
  • That makes so much more sense. Thank you very much. Backbone is a difficult one to wrap your head around. – MikeD Mar 21 '12 at 15:05