Backbone Fetch Related Models

匿名 (未验证) 提交于 2019-12-03 02:34:02

问题:

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.

回答1:

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'     } }) 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!