Search code examples
javascriptbackbone.jsbackbone-relational

Backbone.js relations


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.


Solution

  • 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
    });