Search code examples
backbone.jsbackbone-viewsbackbone.js-collections

How to fetch the model in a view with a dynamic url defined in a view


I am using backbone.js in my app. My model named MyModel is

Backbone.Model.extend({
    urlRoot: 'home'
  });

Need to fetch model with url "home/abc/xyz" where "abc" and "xyz" are dynamic in my view. I did the following

var model = new MyModel({id:'abc/xyz'});
    model.fetch();

but its not working. It goes to url "home/abc?xyz".

How should i solve this issue?


Solution

  • Here is the url function of Backbone.Model which is responsible for such kind of behavior in Backbone:

    url: function() {
      var base =
        _.result(this, 'urlRoot') ||
        _.result(this.collection, 'url') ||
        urlError();
      if (this.isNew()) return base;
      return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
    }
    

    As you can see encodeURIComponent(this.id) will encode your id, so you can't pass and '/' -> '%2F'. You always can rewrite this function, but I guess it's not the best idea, cause it can break another things.

    I can suggest you another approach:

    Just define urlRoot of your model as function and there do your job:

    var yourModel = Backbone.Model.extend({
        defaultUrl: 'home',
        urlRoot: function () {
            return defaultUrl + this.get('yourUrlAttribute');
        }
    });
    

    Just pass the yourUrlAttribute as model attribute when creating it and fetch the model.

    Having in mind this approach and that Backbone.Model will append encoded 'id' as the last part of URL (when you fetching model) you can get what you want.