I’m trying to override Backbone.sync in order to set the “id” attribute every time we fetch a model. This way, I am sure the next model.save() will fire an update and not a create, even if the fetch() didn’t respond with an id.
Backbone._sync = Backbone.sync;
Backbone.sync = function(method, model, options) {
var params = _.clone(options);
params.success = function(model) {
if(method == 'read' && model.isNew()) {
var id = Math.floor(Math.random()*1000);
model.set({ "id": id });
}
if(options.success) options.success(model);
};
Backbone._sync(method, model, params);
}
But the model passed to the success function seems not to be a Backbone model, but just an object. So I can’t use any method (like model.isNew()) on it. Any idea of what I did wrong?
It sounds like you might want to override
Model.fetchorModel.parseinstead ofBackbone.sync.Backbone.syncjust takes$.ajax()options, so thesuccesscallback is just receiving the JSON response from the server, not an instantiated model.The default
Model.fetch()callback looks like this:Here
modelrefers to the current instance, as you intend. So you might consider overridingModel.fetchto add an id if it’s not there, or, probably better, overridingmodel.parse(), which is a passthrough by default and is intended as a hook for you to munge the server data. I’m not thrilled with your random number id implementation, as there’s still a chance of collisions, especially if you’re making a lot of models – you might try usingmodel.cid(guaranteed to be unique in the client, though it might have collisions with server-provided IDs) or Underscore’s _.uniqueId():