Backbone.js collection options

前端 未结 2 1894
故里飘歌
故里飘歌 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/<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.

    0 讨论(0)
  • 2021-01-30 11:08

    The way you have the url property declared, the value will be determined once when the browser initially loads the javascript file, and 'id' will be undefined.

    The Backbone.Collection accepts options as the second argument in its constructor, so you can pass the id value as an option, and then set the url value within the initialize function of the collection.

    Here's an example

    var Messages = Backbone.Collection.extend({
      initialize: function(models, options) {
        this.url = 'http://url/messages/' + options.id;
      },
      model: Message,
    });
    
    var collection = new Messages([], { id: 2 });
    collection.fetch();
    
    0 讨论(0)
提交回复
热议问题