OrangeTux
OrangeTux

Reputation: 11461

How to retrieve a collection based on a model in backbone

I want to retrieve a collection of keywords of a file with an POST request like this:

api.host.com/file/4/keywords

But how do I have to define my url and urlRoot Keyword model and keyword collection? I've read the docs, but I could not figured it out.

Upvotes: 1

Views: 83

Answers (1)

namero999
namero999

Reputation: 3002

As usual, in general but especially in JS, there are many ways to do that. I can tell you a couple of ways I would do that.

1) I would define a keywords Collection as

Keywords = Backbone.Collection.extend( { ... } )

Then use it as a property of the File Model and I would set the correct value during initialize()

File = Backbone.Model.extend({

    // the empty array [] is the initial set of models
    this.keywords = new Keywords([], { url: '/file/' + this.id + '/keywords' });

})

This way you can call file.keywords.fetch() to get the content.

2) I would define a keywords Collection as

Keywords = Backbone.Collection.extend({

    initialize: function(models, options) {
        this.modelId = options.modelId
    },

    url: function() {
        return '/file/' + this.modelId + '/keywords'
    }

});

And then, when needed, I would create instance like this:

File = Backbone.Model.extend({

    this.keywords = new Keywords([], { modelId: this.id });

})

To give you a complete answer, you could actually drop the initialize() function (if you don't need it) and write and url function as

url: function() {
    return '/file/' + this.options.modelId + '/keywords'
}

Upvotes: 3

Related Questions