Backbone.js collection options

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

    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();
    

提交回复
热议问题