Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js set URL parameters in model & use it with fetch

I would like to fetch model from specific url with parameter: url: server/somecontroller/id/?type=gift

Simple working way is:

collection.fetch({ data: { type: 'gift'} });

But I want to set it in model:

    ...
    if(id){
      App.coupon = new AffiliatesApp.Coupon({id: id});
    } else {
      App.coupon = new AffiliatesApp.Coupon({id: 'somecontroller'}, {type: 'gift'});
    }
    App.coupon.fetch();

How can I achieve it?

like image 515
jmav Avatar asked Sep 20 '12 22:09

jmav


1 Answers

The easiest way to achieve this is to override Backbone's url method on the Coupon model with one defined by you. For example you can do :

Affiliates.Coupon = Backbone.Model.extend({
  urlRoot : "server/somecontroller/",
  url : function(){
    var url = this.urlRoot + this.id;
    if(this.get("type")){
      url = url + "/?type=" + this.get("type");
    }
    return url;
  }
});

This solution is easy to implement but has a drawback: the generated URL will be used for every action that syncs to the server (fetch,save,..).

If you need to have a finer control over the generation of the URL depending on what action you are doing you will need to override Backbone's Sync method for your model.

like image 107
Beorn Avatar answered Oct 24 '22 08:10

Beorn