私はあなたがrequireJSを使用していると仮定していますちょうど生命維持
にAMDを変換しない場合
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 abortAllPendingXhrs = function() {
underscore.invoke(xhrArray, "abort"),
xhrArray = []
};
// here options can contain the text which you want to show on spinner and toaster
var showSpinnerandToaster = function(method, options) {
if("create" === method || "update" === method || "patch" === method) {
//show saving spinner
}
if("read" === method) {
//show fetching spinner
}
//using once here because none of this will be called twice
//'sync' event is fired on the model/collection when ajax gets succeeded
this.once("sync", function() {
//hide the spinner and show success toaster
//remove cancelRequest since now on you can not abort the AJAX
delete this.cancelRequest;
//remove error callback since it will not be called now
this.off("error");
});
//'error' event is fired on the model/collection when ajax fails
this.once("error", function(model, xhr) {
//show error toaster if the xhr.statusText !== "abort"
//remove cancelRequest since now on you can not abort the AJAX
delete this.cancelRequest;
//remove sync callback since it will not be called now
this.off("sync");
});
};
vent.on("abortAllPendingXhrs", abortAllPendingXhrs);
backbone.Model.prototype.sync = backbone.Collection.prototype.sync = function(method, model, options) {
var proxiedShowSpinnerandToaster = underscore.bind(showSpinnerandToaster, this);
proxiedShowSpinnerandToaster(method, options)
var xhr = backbone.sync.apply(this, arguments);
xhrArray.push(xhr);
xhrArray = underscore.reject(xhrArray, function(xhr) {
//remove all xhrs which are completed since we can not abort them
return 4 === xhr.readyState
}),
this.cancelRequest = function(){
//invoke cancelRequest on model if you want to abort the AJAX call
xhr.abort();
}
return xhr;
}
});
こんにちはニキル、別にここにこれを掲示から、私はそれがここにBackboneJSのためのSOのドキュメントを更新してもいいだろうと思う - のhttp: //stackoverflow.com/documentation/backbone.js/topics –
@ DavidR確かに私はそうするでしょう。 –
ありがとうNikhil! :-) –