Skip to content

Instantly share code, notes, and snippets.

@dericcrago
Created February 22, 2012 17:25
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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) == '/' ? '' : '/');
}
});
@owais
Copy link

owais commented Jan 24, 2013

A more readable version would be

return origUrl += origUrl.endsWith('/') ? '' : '/'

@lemieux
Copy link

lemieux commented Jun 4, 2013

endsWidth is not a standard method for a string. In plain js without any modification to String.prototype, your example doesn't work.

@owais
Copy link

owais commented Jul 20, 2013

You are right. I was working with Firefox at the time and didn't realize that it was not available everywhere :)

@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