我正在尝试在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
}
});
答案 0 :(得分:0)
将选项传递给xhr
对象(XMLHttpRequest
对象)的简单方法是使用jQuery ajax function的xhrFields
选项。由于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函数,例如fetch
,save
,{{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
属性。