$.ajax() 的beforeSend 回调接收 2 个参数:
发送前
类型:函数(jqXHR jqXHR,PlainObject 设置)
如您所见,第二个参数是settings,它接收传递给“Backbone.Collection”或Backbone.Model 的fetch 方法的所有选项:
示例:
您的 ajax 设置:
$.ajaxSetup({
beforeSend: function (xhr, options) {
console.log(options.testVar); // Will be "Hello" when collection fetched
}
});
当您执行 fetch() 或以某种方式与服务器交互时放置:
yourCustomCollectionOrModel.fetch({testVar: "Hello"}).done(function(){
// bla bla
})
所以每当yourCustomCollectionOrModel 获取testVar 时,都会传递给beforeSend 的options 参数。
注意:如果您能以更喜欢的方式解决问题,请避免使用全局变量。
如果您不想在获取集合或模型时重复相同的操作,您可以更好地进行事件。
只需重写 fetch() 方法,并将特定于集合/模型的标志添加到选项中。
示例
var TestCollection = Backbone.Collection.extend({
url: 'your/api/path',
fetch: function (options) {
options = options || {};
options.testVar = 'Hello';
return this.constructor.__super__.fetch.call(this, options);
}
});
更新:
实现相同行为的另一种可能是最短的方法是像这样包装Backbone.sync:
var oldSync = Backbone.sync;
Backbone.sync = function(method, model, options) {
options = options || {};
options.modelContext = model;
return oldSync.call(Backbone, method, model, options);
}
这样你就不需要重写 fetch,或者手动将选项传递给fetch() 方法。
还有 $.ajax 的 beforeSend 回调:
$.ajaxSetup({
beforeSend: function (xhr, options) {
console.log(options.modelContext); // this will be the model's or collection's instance
}
});
希望这会有所帮助!