我在我的 Node 应用程序中使用 Backbone.js。我正在从 View 、模型和集合中调用各种 ajax 调用。我已经创建了我的自定义属性,例如每个 View 、模型和集合中都有“myName”,并为每个 View 、模型和集合分配了唯一的名称。现在我想在ajax“beforeSend”中使用这个“myName”属性,所以我应该知道这个ajax是从哪个 View 或模型中调用的。有什么选择可以做到这一点吗?
最佳答案
beforeSend
回调接收 2 个参数:
beforeSend
Type: Function( jqXHR jqXHR, PlainObject settings )
如您所见,第二个参数是 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
时,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
}
});
希望这有帮助!
关于node.js - Backbone.js - 在 ajax 中获取 View 、模型或集合属性 'beforeSend',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27479489/