骨干获取相关型号 [英] Backbone Fetch Related Models

查看:97
本文介绍了骨干获取相关型号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作中的骨干应用程序,但一切到目前为止,我读过或者是有关显示项目列表(例如,待办事项列表)或单个项目。

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.

现在我有用户,每个用户拥有的技能列表(pretty就像任何游戏)。我可以轻松地获得所有用户或单个用户,同样的技能,但如果我想获得的所有技能,给定用户呢?我会怎么做呢?

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

但我没有与骨干经验丰富,我真的不喜欢的这个想法,还要求将类似于 / someUrl?USER = 1 我宁愿避免, / someUrl /用户/ 1 会好得多。

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.

我也注意到 BackboneRelational ,但我还没有真正尝试过它,它似乎有点矫枉过正,为我的问题,但也许我错了。

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.

推荐答案

我强烈建议你签这个<一个href=\"http://lostechies.com/derickbailey/2012/04/05/composite-views-tree-structures-tables-and-more/\"相对=nofollow>帖子,相信你会找到答案。如果短期你可能有以下方法无需任何额外的插件,并建立嵌套模式:

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 :

预计以下JSON:

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

让更新用户模型:

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

然后创建S​​killsCollection

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

技能模型:

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

这篇关于骨干获取相关型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆