Keith Jackson Keith Jackson - 7 months ago 33
Javascript Question

Backbone.js with a custom fetch URL

I am trying to set up a variant fetch method on my backbone model that will fetch the current model for a given user. This is available from the API on

/api/mealplans/owner/{username}/current
.

I have written the following model. I commented out the URL Root, as the prototype fetch call was simply using the
urlRoot
and I wanted to see if that was overriding the url parameter I passed in portions somehow.

var mealPlan = Backbone.Model.extend({
name: 'Meal Plan',
//urlRoot: '/api/mealplans',
defaults: {},
fetchCurrent: function (username, attributes, options) {
attributes = attributes || {};
options = options || {};
if (options.url === undefined) {
options.url = "/api/mealplans/owner/" + username + "/current";
}
return Backbone.Model.prototype.fetch.call(this, attributes, options);
},
validate: function (attributes) {
// To be done
return null;
}
});


I've seen this done, in some variations in other places, such as at backbone.js use different urls for model save and fetch - In that case the code is slightly different (I started with that and broke it down to make it easier for me to read.)

The options object has the url parameter in it fine when I pass it to fetch, but then it seems to ignore it!

Answer

I was assuming the same parameters to fetch as to save - This is not the case.

The method signature for fetch ONLY takes 'options' and not 'attributes', hence the url parameter wasn't found.

The model code should look a bit more like this..

   var mealPlan = Ministry.Model.extend({

        name: 'Meal Plan',
        urlRoot: '/api/mealplans',

        defaults: {
        },

        fetchCurrent: function (username, options) {
            options = options || {};
            if (options.url === undefined) {
                options.url = this.urlRoot + "/owner/" + username + "/current";
            }

            return Backbone.Model.prototype.fetch.call(this, options);
        },

        validate: function (attributes) {
            // To be done
            return null;
        }
    });
Comments