backbone sync override, append url with query string? backbone sync override, append url with query string? ajax ajax

backbone sync override, append url with query string?


I don't think you need to override sync at all:

var globalKey = 'key123';var urlWithKey = function(url, key) {    return function() {        return url + "?key=" + key;    };};var MyModel = Backbone.Model.extend({    url: urlWithKey('/my/url/', globalKey)});

If you now create an object and save it, a POST request to my/url/?key=key123 is sent.I guess you could also override the url method if this is the behavior you need for all of your Backbone models.

A general note: in Backbone most parameters, such as url can be a function or a value. I don't know why in your example it was a function once and a value in another case, but you always must be able to handle both ways if you override some of the internal functions. If you look at Backbone's sourcecode you will see that they use getValue to access these parameters:

var getValue = function(object, prop) {    if (!(object && object[prop])) return null;    return _.isFunction(object[prop]) ? object[prop]() : object[prop];};

Update: Overloading the url method for all models could work like this:

var globalKey = 'key123';(function() {    var baseUrl = Backbone.Model.prototype.url;    Backbone.Model.prototype.url = function() {        return this.baseUrl + "?key=" + globalKey;    };})()var MyModel = Backbone.Model.extend({   baseUrl: '/my/url/'});

You could also leave the regular Backbone.Model as it is, and create your own base class. See http://documentcloud.github.com/backbone/#Model-extend for details.


Just set your URL like so:

url : function() {        return  "/my/url" + this.key;    }

In your overridden .sync, you only need to set the key property.