Search code examples
javascriptbackbone.js

Backbone Fetch Related Models


I'm working on a Backbone app, but everything I've read so far is either about displaying a list of items (a TODO list for example) or a single item.

Right now I have users, each user has a list of skills (pretty much like any game). I can easily get all users or a single user, the same for the skills but what if I want to get all the skills for a given user? How would I do that?

I thought about just adding a property to the users with a new instance of a collection, something like this:

var Users = Backbone.Model.extend({
  skills: new Skills({ user: this })
});

var Skills = Backbone.Collection.extend({
  model: Skill,
  url: '/someUrl',
  initialize: function (options) {
    // fetch all skills from an user
    this.fetch({ data: { user: options.user.get('id') } });
  }
});

But I don't have much experience with Backbone and I don't really like the idea of that, also the request would look something like /someUrl?user=1 which I'd rather avoid, /someUrl/user/1 would be much better.

I've also noticed BackboneRelational but I haven't really tried it, it seems a bit of an overkill for my problem, but maybe I'm wrong.

What approach should I take to fetch all of my users skills? Thanks in advance.


Solution

  • I highly recommend you to checkout this post, sure you will find an answer. If short you may have following approach without any additional plugins and build nested model :

    expect following json:

    {
       name: 'Gorbachov',
       age: '75',
       skills: [
           {
               name: 'kalashnikov'
           }, 
           {
               name: 'vodka'
           },
           {
               name: 'balalaika'
           }
       ]
    }
    

    lets update User model:

    User = Backbone.Model.extend({
        initialize: function(){
            var skills = this.get("skills");
            if (skills){
                this.skills = new Skills(skills);
                this.unset("skills");
            }
        }        
    })
    

    Then create SkillsCollection:

    SkillsCollection = Backbone.Collection.extend({
        model: Skill
    })
    

    and Skill model:

    Skill = Backbone.Model.extend({
        defaults: {
            name: 'unnnamed'
        }
    })