javascripturlbackbone.jsfetch-api

Backbone .fetch() clean data rewriting


I'd like to make a clean request with backbone on a fetch call. My API's URL is /users/, and I want to pass data :

var users = new UsersCollection({ users_id: "1|2|3" });
users.fetch({
        data: "users_id=1|2|3"
    });

Users is a collection of UserModel.

But the url becomes /users/?users_id=1|2|3 but I want it to be /users/1|2|3.

I've a .htaccess with the following line RewriteRule ^(.*)/$ /api.php?fct=$1 [L]

How can I do it ?


Solution

  • I think that using query params for specifying which models the REST api should ask for is better than the "1|2|3" syntax, but if the specifications is to generate a /users/1|2|3 url it can be achieved like this:

    var UsersCollection =  Backbone.Collection.extend({
      initialize: function(models, options){
        this.requestedModelsId = options.modelsId;
      },
      url: function(){
        return "/users/" +  this.requestedModelsId.join("|"); //generates  /users/1|2|3 if for requestedModelsId [1,2,3]
      }
    });
    
    
    var users = new UsersCollection(undefined, {modelsId : [1,2,3]});
    users.fetch();
    

    This way the responsibility is left for the collection to know what to fetch for and how to fetch it.