Backbone.js collection options

@Paul’s answer is good, but it’s also worth noting that the url attribute can be a function. In my opinion (and it’s just opinion, since the end result is the same), the code is a little more legible, if more verbose, if you set the id in initialize and the reference it in a function:

var Messages = Backbone.Collection.extend({
  initialize: function(models, options) {
    this.id = options.id;
  },
  url: function() {
    return '/messages/' + this.id;
  },
  model: Message,
});

var collection = new Messages([], { id: 2 });
collection.fetch();

Just to make sure, though – you aren’t confusing the id here with the Model id, are you? @Paul’s answer, and my code above, assume that you have multiple Messages collections, each with its own id. If the API path /messages/<id> actually refers to a message, not a set of messages, then you only need to set the url to /messages/ in the Collection, and Backbone will automatically use /messages/<id> for each model.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)