Assuming you are implementing requireJS; if not, convert AMD to IIFE
define("vent", ["backbone", "backbone.marionette"], function(backbone) {
return new backbone.Wreqr.EventAggregator
});
define("backbone-sync", ["backbone", "underscore", "vent"], function(backbone, underscore, vent) {
var xhrArray = [];
var stopAllRequests = function() {
underscore.invoke(xhrArray, "abort"),
xhrArray = []
};
// specify the text to display on spinner and toaster based on options
var displaySpinnerAndToaster = function(method, options) {
if ("create" === method || "update" === method || "patch" === method) {
// show saving spinner
}
if ("read" === method) {
// show fetching spinner
}
this.once("sync", function() {
// hide spinner and show success toaster
delete this.cancelRequest;
this.off("error");
});
this.once("error", function(model, xhr) {
// show error toaster if xhr.statusText !== "abort"
delete this.cancelRequest;
this.off("sync");
});
};
vent.on("stopAllRequests", stopAllRequests);
backbone.Model.prototype.sync = backbone.Collection.prototype.sync = function(method, model, options) {
var displaySpinnerAndToasterProxy = underscore.bind(displaySpinnerAndToaster, this);
displaySpinnerAndToasterProxy(method, options)
var xhr = backbone.sync.apply(this, arguments);
xhrArray.push(xhr);
xhrArray = underscore.reject(xhrArray, function(xhr) {
return 4 === xhr.readyState
}),
this.cancelRequest = function() {
xhr.abort();
}
return xhr;
}
});