Skip to content

Instantly share code, notes, and snippets.

@dericcrago
Created February 22, 2012 17:25
Show Gist options
  • Save dericcrago/1886177 to your computer and use it in GitHub Desktop.
Save dericcrago/1886177 to your computer and use it in GitHub Desktop.
add trailing slash to Backbone.Model urls
// example
User = Backbone.Model.extend({
url: function() {
var origUrl = Backbone.Model.prototype.url.call(this);
return origUrl + (origUrl.charAt(origUrl.length - 1) == '/' ? '' : '/');
}
});
@LukePeters
Copy link

Thanks for this. Worked just fine for me.

@giiska
Copy link

giiska commented Jul 23, 2014

This is not good solution, I prefer wrapper Backbone.Sync method to modify the model's url.

@yellowcap
Copy link

Here is a combination of above answers that worked for me

var _sync = Backbone.sync;
Backbone.sync = function(method, model, options){

    // Add trailing slash to backbone model views
    var _url = _.isFunction(model.url) ?  model.url() : model.url;
    _url += _url.charAt(_url.length - 1) == '/' ? '' : '/';

    options = _.extend(options, {
        url: _url
    });

    return _sync(method, model, options);
};

@FeroxTL
Copy link

FeroxTL commented Oct 19, 2016

Here is a version, that handles GET params in correct way

var _sync = Backbone.sync;
Backbone.sync = function(method, model, options){
    // Add trailing slash to backbone model views
    var parts = _.result(model, 'url').split('?'),
        _url = parts[0],
        params = parts[1];

    _url += _url.charAt(_url.length - 1) == '/' ? '' : '/';

    if (!_.isUndefined(params)) {
        _url += '?' + params;
    };

    options = _.extend(options, {
        url: _url
    });

    return _sync(method, model, options);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment