Backbone.js – 在ajax中获取视图,模型或集合属性'beforeSend'
我在我的节点应用程序中使用Backbone.js。 我从视图,模型和colllection调用各种ajax调用。 我已经在每个视图,模型和集合中创build了自定义属性,例如“myName”,并为每个视图分配了唯一的名称。 现在我想要在ajax“beforeSend”这个“myName”属性,所以我应该知道从哪个视图或模型,这个ajax被调用。 有没有这样做的select?
$ .ajax()的 beforeSend
callback接收2个参数:
beforeSend
types:函数(jqXHR jqXHR,PlainObject设置)
正如你所看到的第二个参数是接收所有传递给'Backbone.Collection'或Backbone.Model
方法的选项的settings
:
例:
你的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
的options
参数。
注意:如果可以用更优选的方式解决问题,则避免使用全局variables。
如果您不想在获取集合或模型时重复相同的事件,则可以更好地进行事件。
只需重写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()
方法。
并在$ .ajax的beforeSendcallback中:
$.ajaxSetup({ beforeSend: function (xhr, options) { console.log(options.modelContext); // this will be the model's or collection's instance } });
希望这可以帮助!
// for example $.ajaxSetup({ beforeSend: function (xhr) { xhr.setRequestHeader('viewName', yourGlobalVariable /* or session storage */); } });
在每个ajax调用(或模型/集合获取,保存等)之前存储在您的视图的yourGlobalVariable
名称。