javascript - 如何获取带有集合和模型 ID 的 URL

标签 javascript backbone.js

我做了一个网站来创建一些 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 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.

关于javascript - 如何获取带有集合和模型 ID 的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40202770/

相关文章:

javascript - 使用 angularJs 重定向到其他项目

javascript - this.initialize(arguments) 与 this.initialize.apply(this, arguments) : what's the difference?

javascript - 如何从 JavaScript 中的对象数组中选取属性?

javascript - D3 强制模拟和拖动,什么是node.fx/node.fy?

javascript - 使动画函数在执行 $.ajax 调用时起作用

javascript - redux-api-middleware 如何对端点进行全局设置

javascript - 异步加载特定 CSS,并在加载时删除等待消息

javascript - 主干监听模型中的对象变化

javascript - 为什么不使用这个参数?

backbone.js - 对使用 Backbone.js 和 Tastypie 从服务器预加载集合一无所知