Reputation: 3223
Is it possible to just simply trigger or call the error callback of save in backbone?
I'm overriding the save function of backbone with this
save: function(attributes, options) {
options || (options = {});
options.timeout = 10000;
options.beforeSend = sendAuthorization;
console.log( options.connection.ConnectionType );
if( options.connection.ConnectionType != 'No network connection' ){
Backbone.Model.prototype.save.call(this, attributes, options);
}else{
console.log("ERROR! network related!");
}
}
options.connection.ConnectionType is simple a string which states the current internet connection of the device (iPad).
this.model.save( this.model,
connection : { ConnectionType : "No network connection" },
success : {...},
error : {...}
}
What I want is if the if statement failed then it should trigger the error callback of the save function. Is it possible? Thanks
Upvotes: 1
Views: 542
Reputation: 35890
At its simplest you can just execute the error
callback function:
if( options.connection.ConnectionType != 'No network connection' ){
Backbone.Model.prototype.save.call(this, attributes, options);
} else {
if(options.error) {
options.error(this, null, options);
}
}
This method has the problem that it doesn't comply to the save
method and error
callback API. The save
method is expected to return an jqXHR
object, and the error callback is expected to have it as the second argument.
If you want to provide an API compatible method/callback signature, the simplest way would be to abort the request. Something like:
var xhr = Backbone.Model.prototype.save.call(this, attributes, options);
if( options.connection.ConnectionType == 'No network connection' ){
xhr.abort();
}
return xhr;
This will cancel the request as soon as it is initiated. You get your xhr/promise return object and the correct xhr parameter to the callback. The status
of the xhr will be 0 and statusText
"abort".
Upvotes: 2