对于那些想知道如何做到这一点的人,这里是我取消 jquery ajax 请求的方法。
首先,我在我的应用商店中定义了一个新方法,它将在我的自定义 RESTAdapter 上调用 cancelQuery。
App.Store = DS.Store.extend({
cancelQuery: function(type){
var adapter = this.adapterFor(this.modelFor(type).modelName);
if(typeof adapter.cancelQuery === 'function'){
adapter.cancelQuery();
}
}
});
在我的自定义 RESTAdapter 中,我定义了这个新函数并像这样覆盖 ajaxOptions:
App.YOURMODELAdapter = DS.RESTAdapter.extend({
jqXHRs: [],
ajaxOptions: function(url, type, hash) {
// Get default AjaxOptions
var ajaxOptions = this._super(url, type, hash);
// If the function was defined in the DS.RESTAdapter object,
// we must call it in out new beforeSend hook.
var defaultBeforeSend = function(){};
if(typeof ajaxOptions.beforeSend === 'function'){
defaultBeforeSend = ajaxOptions.beforeSend;
}
ajaxOptions.beforeSend = function(jqXHR, settings){
defaultBeforeSend(jqXHR, settings);
this.jqXHRs.push(jqXHR); // Keep the jqXHR somewhere.
var lastInsertIndex = this.jqXHRs.length - 1;
jqXHR.always(function(){
// Destroy the jqXHRs because the call is finished and
// we don't need it anymore.
this.jqXHRs.splice(lastInsertIndex,1);
});
};
return ajaxOptions;
},
// The function we call from the store.
cancelQuery: function(){
for(var i = 0; i < this.jqXHRs.length; i++){
this.jqXHRs[i].abort();
}
}
});
现在,您可以cancelQuery
在控制器的上下文中调用。
this.store.cancelQuery('yourmodel');