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

2

9

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?

Taw answered 20/9, 2012 at 22:22 Comment(0)
D
10

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.

Dianthus answered 21/9, 2012 at 19:48 Comment(0)
M
0

It can be done by overriding the fetch method in model to use some custom data. Using CoffeeScript it could 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 adjusted for any override logic.

Mehitable answered 26/2, 2015 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.