-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone-sync-deferred.js
47 lines (38 loc) · 1.26 KB
/
backbone-sync-deferred.js
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';
// CommonJS support for easier testing
(function(root,factory, undefined){
if (module !== undefined) {
// CommonJS
module.exports = factory(
require('backbone'),
require('jquery')
);
} else {
// Browser mode. Just inject manually the dependencies that should be defined in
// the global window scope.
root.Backbone.sync = factory(root.Backbone, root.$);
}
})(this,function(Backbone, $){
// Keep track of original sync
var origSync = Backbone.sync;
var newSync = function(method, model, options) {
// Keep track of original callbacks to have a seamless integration
var origSuccess = options.success;
var origError = options.error;
// Let's get a nice promise
var deferred = $.Deferred();
// Override success
options.success = function(model, response, options) {
if (origSuccess) origSuccess(model, response, options);
return deferred.resolve(model);
};
// Override error
options.error = function(model, response, options) {
if (origError) origError(model, response, options);
return deferred.reject(response);
};
origSync(method, model, options);
return deferred.promise;
};
return newSync;
});