Backbone.js collection options

前端 未结 2 1900
故里飘歌
故里飘歌 2021-01-30 10:56

I have written a model/view/collection using Backbone.js. My collection uses the fetch method to load the models from a remote server. The url required for this collection needs

2条回答
  •  一个人的身影
    2021-01-30 11:08

    @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/ 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/ for each model.

提交回复
热议问题