Search code examples
urlbackbone.jsfile-extension

Use .JSON for Backbone Model URL


I would like to change the url to end with .json in Backbone. Here's my issue:

I want to use the same URI for the HTML version of my site and the JSON API (used by the HTML version). So both my URIs should look like

GET website.com/users/1 to get info about the user with id 1 in HTML. The HTML page fetches website.com/users/1.json.

Howewer, backbone doesn't let me change the extension of the url of my models:

var User = Backbone.Model.extend({
  url:'users.json'
});

does'nt work

I understand that Backbone doesn't integrate the idea of extension in its URL, so what possibilitys do I have ?


Solution

  • You can override url function, and in that function you can generate url you want :

    url: function(){
       return 'users/'+this.id+'.json'
    }
    

    backbone documentaion