secret
Last active

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// This model allows to change the id, but save/put the model to the old Id
var ChangeableIdModel = Backbone.Model.extend({
set: function(attr, options) {
if (attr && attr['id'] && !this.oldId ) this.oldId = this.get('id');
Backbone.Model.prototype.set.call(this, attr, options);
return this;
},
url: function() {
var base = getUrl(this.collection) || this.urlRoot || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.oldId || this.id);
},
save: function(attr, options) {
options || (options = {});
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
if (model.changedId) delete model.oldId;
if (success) success(model, resp, xhr);
};
Backbone.Model.prototype.save.call(this, attr, options);
}
});
 
var getUrl = function(object) {
if (!(object && object.url)) return null;
return _.isFunction(object.url) ? object.url() : object.url;
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.