Abdelghani AINOUSS
Abdelghani AINOUSS

Reputation: 180

Loading Backbone model by custom attribute

Lets say, I have the following Backbone model :

var Meal = Backbone.Model.extend({
defaults: {
"appetizer":  "caesar salad",
"entree":     "ravioli",
"dessert":    "cheesecake"
},
urlRoot : api/meals,
idAttribute : id, 
// some other stuff
});

Assuming that I have a backend Spring MVC conroller that intercept GET requests, so when I fetch my model, using

myMeal.fetch();

my model gets loaded from the server. for now everything is clear, my question is, what if I have another method on the backend that takes a string as parameter and return as responsebody, the right json element. how can I make that call from my model ? I'm looking for something like this :

var meal = new Meal({'entree': 'value'});
meal.fetch({
 // if there is no id, and 'entree' is given, I want to call   /  
 //  api/findByEntree passing this.entree as parameter. 
});

I want to make an Ajax call from the object itself to the backend, by specifying the url inside the Backbone model.

Upvotes: 0

Views: 125

Answers (2)

Matt Derrick
Matt Derrick

Reputation: 5724

urlRoot can be a function so no need to override fetch. I believe you could just do something like this:

var Meal = Backbone.Model.extend({
    defaults: {
        "appetizer": "caesar salad",
        "entree": "ravioli",
        "dessert": "cheesecake"
    },
    urlRoot : function() {
         return 'api/' + this.get('id') ? 'meals' : 'findByEntree';
    },
    idAttribute : id, 
    // some other stuff
});

Upvotes: 1

ffflabs
ffflabs

Reputation: 17481

You can override the default fetch, intercept the call, do some verification and then pass onto the original fetch:

var Meal = Backbone.Model.extend({
    fetch: function(options) {
        if(this.has('id')) {
          Backbone.Model.prototype.fetch.call(this, options);
        } else {
          this.findByEntree(options);
        }
    },
    fetchByEntree: function(options) {
        ...
    }
});

however, keep in mind that you'll need some extra logic to deal with the case of trying to fetch a new Meal, which won't have neither id nor entree.

Upvotes: 1

Related Questions