Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an url with collection and model ids

I made a website to create some maps. So, all my maps have an id, and my map has some elements with ids.

So I create a collection Map with an id and its model is my map object :

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

But my model have an id too. I don't know for a model how to return url with a collection id.

I need to return /api/maps/id_collection/id_model.

like image 557
Romain Caron Avatar asked Nov 20 '25 08:11

Romain Caron


1 Answers

When a model is added to a collection, it receives a reference to the collection. So each model has a collection property this.collection set if it's in a collection.

From the Backbone model constructor documentation (emphasis mine):

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.

Then, you could use that to build the full url of a model:

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

Note that the default url for a model is what you want.

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.

like image 173
Emile Bergeron Avatar answered Nov 21 '25 20:11

Emile Bergeron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!