How to set a Collection's url

2019-02-03 00:21发布

let's say I have :

var Book = Backbone.Model.extend();

var Collection = Backbone.Collection.extend({
  model: Book,
  url: '/books',
  initialize: function(){
    this.fetch();
  })
})

How can I change the Collection's url when instantiating a new collection ?

var AdventureBooks = new Books({ url: '/books/adventure' }) does not work

var AdventureBooks = new Books({ category: 'adventure' })

and in the Collection definition:

url : '/books/' + this.category does not work either.

Thanks.

标签: backbone.js
8条回答
女痞
2楼-- · 2019-02-03 01:06
var Book = Backbone.Model.extend({
  "url": function() {
    return '/books/' + this.get("category");
  }
});
查看更多
SAY GOODBYE
3楼-- · 2019-02-03 01:09

If you want to have dynamic urls for your collection, try this (tested with backbone 1.1.2):

Create an instance of your backbone collection and pass the dynamic url parameter as an option (the options object needs to be the the second argument as the first one is an optional array of models):

var tweetsCollection = new TweetsCollection(null, { userId: 'u123' });

Then inside of your collection, create a dynamic url function that uses the value from the options object:

var TweetsCollection = Backbone.Collection.extend({
    url: function() {
        return '/api/tweets/' + this.options.userId;
    },
    model: TweetModel
});
查看更多
登录 后发表回答