骨干模块化模式与xhr取指令

时间:2016-11-20 02:33:52

标签: javascript jquery backbone.js

我正在尝试在ajax请求中使用alter xhr对象。我正在对集合进行fetch调用。但是当我改变xhr时,我得不到任何数据。这样做的目的是显示加载器的百分比,但当我返回新的xhr对象时,xhr甚至不起作用。我检查了返回的xhr,url指向/ admin / categories

    require(['views/categories', 'models/categories', 'helpers/helper'], function(CategoriesView, model, helper) {

    var categories = new model.CategoriesCollection;

    categories.fetch({ url: "/admin/categories/getcategories", xhr: helper.xhr('#main-loader') }).then(function(response) {
        console.log(response);
    });
});         

这是我的帮助文件

define(['helpers/helper', 'require'], function(Helper, require) {

    'use strict';

    var $ = require('jquery');
    var Backbone = require('backbone');

    var xhr = function(loaderId) {

        var _xhr = Backbone.$.ajaxSettings.xhr();        

        _xhr.addEventListener("progress", function(e){      

            if (e.lengthComputable) {

                console.log(e);
            }
        }, false);
        return _xhr;
    }

    return  {    
        xhr: xhr        
    }
});

1 个答案:

答案 0 :(得分:0)

将选项传递给xhr对象(XMLHttpRequest对象)的简单方法是使用jQuery ajax functionxhrFields选项。由于Backbone.sync默认情况下在后台使用jQuery.ajax,因此传递给Backbone同步功能的所有选项都会作为ajax选项传递。

简单的一次性解决方案

检查进度的最简单示例:

myCollection.fetch({
    url: root + '/photos/',
    xhrFields: {
        onprogress: function() {
            console.log("options onprogress");
        }
    }
});

永久解决方案

但更方便的方法是覆盖全局Backbone.sync函数,以添加我们自己的progress回调选项和自定义progress事件。

覆盖Backbone.sync

警告:如果您正在编写将要共享的库或代码,请不要覆盖Backbone核心。

Backbone.sync = (function(syncFn) {
    return function(method, model, options) {
        options = options || {};
        var context = options.context,
            progress = options.progress,
            xhrFields = options.xhrFields || {},
            onprogress = xhrFields.onprogress;

        xhrFields.onprogress = function(e) {
            var params = [model, e.loaded, _.extend({}, options, { event: e })];
            if (progress) progress.apply(context, params)
            if (onprogress) onprogress.apply(this, arguments);
            model.trigger(['progress'].concat(params));
        };

        options.xhrFields = xhrFields;

        return syncFn.apply(this, arguments);
    };
})(Backbone.sync);

如何使用

使用起来非常简单:

var myCollection = new Backbone.Collection(),
    root = 'https://jsonplaceholder.typicode.com';

它提供自定义progress事件。

myCollection.listenTo(myCollection, 'progess', function(collection, value, options) {
    console.log("collection progress event");
});

它还提供了一个自定义progress回调,可以传递给在后台调用Backbone.sync的任何Backbone函数,例如fetchsave,{{1} }。此外,传递destroy仍然按预期工作。

xhrFields

除了本机进度事件(myCollection.fetch({ url: root + '/photos/', success: function() { console.log(myCollection.models); }, // custom options callback progress: function(collection, value, options) { console.log("collection onprogress callback"); }, // this still works xhrFields: { onprogress: function() { console.log("options onprogress"); } } }); )之外,您还会收到集合或模型,已加载的数据计数以及options对象,其中包含同步的所有选项。

请注意,它不是那么有用,因为总数并不总是有效。例如,在Chrome中,总数始终为零,但在Firefox中,总数是正确的。您应该检查options.event属性。