当前位置: 动力学知识库 > 问答 > 编程问答 >

rest - How to fetch a collection from a path like "users/:userId/roles" where :userId is dynamic

问题描述:

Backbone can fetch a model by ID, but what if I want to fetch a collection based on a resouce ID, for example "api/users/:userId/roles/" where :userId is dynamic. How do I implement this in Backbone? I don't want to populate the userModel.roles property for every model in the collection fetched from api/users/

网友答案:
var Roles = Backbone.Collection.extend({
    url: function(){
        var url = '/api/users/' + this.user.id + '/roles';
        return url;
    }
});

That's the bare minimum, assuming your User model is a property on the Roles collection. I'd consider looking into abstracting relations away into a AssociatedModel and AssociatedCollection, or looking into the many Backbone plugins available.

网友答案:

Many backbone properties can take a function instead of a string which allows you to be more flexible if you need to be. If you look at the example for url in the documentation you'll see an example of that

// Or, something more sophisticated:

var Notes = Backbone.Collection.extend({
  url: function() {
    return this.document.url() + '/notes';
  }
});

In your case you would probably want something like the following

url: function () {
    //myUserID should probably be coming from your model or somewhere
    return 'api/users/' + myUserID + '/roles/'; 
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: