我做了一个网站来创建一些 map 。所以,我所有的 map 都有一个 id
,并且我的 map 有一些带有 id 的元素。
所以我创建了一个带有 id 的集合 Map,它的模型是我的 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。我不知道模型如何返回带有集合 ID 的 url。
我需要返回 /api/maps/id_collection/id_model
。
最佳答案
当一个模型被添加到一个集合中时,它会收到一个对该集合的引用。所以每个模型都有一个集合属性 this.collection
如果它在集合中则设置。
来自主干 model constructor文档(强调我的):
If you pass a
{collection: ...}
as the options, the model gains acollection
property that will be used to indicate which collection the model belongs to, and is used to help compute the model's url. Themodel.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 expliciturlRoot
if the model's collection shouldn't be taken into account.
关于javascript - 如何获取带有集合和模型 ID 的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40202770/