Created
February 22, 2012 17:25
-
-
Save dericcrago/1886177 to your computer and use it in GitHub Desktop.
add trailing slash to Backbone.Model urls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// example | |
User = Backbone.Model.extend({ | |
url: function() { | |
var origUrl = Backbone.Model.prototype.url.call(this); | |
return origUrl + (origUrl.charAt(origUrl.length - 1) == '/' ? '' : '/'); | |
} | |
}); |
endsWidth is not a standard method for a string. In plain js without any modification to String.prototype, your example doesn't work.
You are right. I was working with Firefox at the time and didn't realize that it was not available everywhere :)
Thanks for this. Worked just fine for me.
This is not good solution, I prefer wrapper Backbone.Sync method to modify the model's url.
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);
};
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
A more readable version would be