如何在骨干中编写http拦截器

时间:2016-09-27 06:07:13

标签: javascript backbone.js marionette

因为我已经在骨干上工作,现在我正在学习角度。我非常喜欢角度赋予功能的方式。我只是在考虑如何在骨干中实现HTTP拦截器,以便在JavaScript使用AJAX保存或从后端获取数据时显示微调器和烤面包机。最终我找到了一种方法。想分享它。希望它能帮到你们所有人。

1 个答案:

答案 0 :(得分:0)

我假设您使用的是requireJS,如果不是将AMD转换为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 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;
    }
});