2016-09-27 6 views
0

私は既にバックボーンで作業していたので、今は角度を学んでいます。私は角度が特徴を与える方法が本当に好きだった。 JavaScriptがAJAXを使用してバックエンドとの間でデータを保存またはフェッチする際に、スピナーとトースターを表示するために、バックボーンにHTTPインターセプターを実装する方法について考えていました。そして結局私はそれを行う方法を見つけました。それを共有する考え。それが皆さんを助けることを願っています。バックボーンにhttpインターセプタを書き込む方法

答えて

0

私はあなたが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; 
    } 
}); 
+0

こんにちはニキル、別にここにこれを掲示から、私はそれがここにBackboneJSのためのSOのドキュメントを更新してもいいだろうと思う - のhttp: //stackoverflow.com/documentation/backbone.js/topics –

+0

@ DavidR確かに私はそうするでしょう。 –

+0

ありがとうNikhil! :-) –

関連する問題