Backbone.js sets URL parameters in the model and uses it with fetch

I would like to get the model from a specific URL with the parameter: url: server / somecontroller / id /? type = gift

Easy way to work:

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

But I want to install it in the 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 this?

+8
marionette
source share
2 answers

The easiest way to achieve this is to override the Backbone url method on the coupon model with the one you define. For example, you can:

 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 is synchronized with the server (fetch, save, ..).

If you need finer control over the creation of the URL, depending on what action you perform, you will need to override Backbone Sync for your model.

+8
source share

This can be done by overriding the sampling method in the model to use some user data. Using CoffeeScript , it might look like this:

 class AffiliatesApp.Coupon extends Backbone.Model fetch: -> super(data: { type: @get('type') }) 

Note that this example will ignore any attributes passed to coupon.fetch() , however it can be easily configured for any override logic.

0
source share

All Articles