如何获得带有集合和模型 ID 的 url

How to get an url with collection and model ids

我做了一个网站来创建一些地图。所以,我所有的地图都有一个 id,我的地图有一些带有 id 的元素。

所以我创建了一个带有 id 的集合 Map,它的模型是我的地图对象:

app.collections.mapDetailsCollection = Backbone.Collection.extend({
    model: app.models.mapDetailsModel,
    initialize: function(options) {
        this.id = options.id;
    },
    url: function () {
        return this.absURL + '/api/maps/' + this.id;
    },
    parse: function(response){
        return response.features;
    },
    toGeoJSON: function(){
        var features = [];
        this.models.forEach(function(model){
            var feature = model.toGeoJSON();
            if (! _.isEmpty(feature.geometry)) {
                features.push(feature);
            }
        });
        return {
            'type': 'FeatureCollection',
            'features': features
        };
    }
});

但是我的模型也有一个 id。我不知道模型如何 return url 使用集合 ID。

我需要 return /api/maps/id_collection/id_model.

将模型添加到集合后,它会收到对该集合的引用。所以每个模型都有一个集合 属性 this.collection 如果它在一个集合中。

来自 Backbone model constructor 文档(强调我的):

If you pass a {collection: ...} as the options, the model gains a collection property that will be used to indicate which collection the model belongs to, and is used to help compute the model's url. The model.collection property is normally created automatically when you first add a model to a collection. Note that the reverse is not true, as passing this option to the constructor will not automatically add the model to the collection. Useful, sometimes.

然后,您可以使用它来构建完整的 url 模型:

var app.models.mapDetailsModel = Backbone.Model.extend({
    urlRoot: function() {
        // Backbone adds the model id automatically
        return this.collection.url() + '/my-model/';
    }
    // ...snip...
});

请注意,模型的默认值 url 就是您想要的。

Generates URLs of the form: [collection.url]/[id] by default, but you may override by specifying an explicit urlRoot if the model's collection shouldn't be taken into account.