Shi*_*nko 2 ajax xmlhttprequest ember.js ember-data
我想知道如何中止请求.
例如,我发布App.MyModel.find(),后来我想在从服务器返回之前取消/中止它.我希望这样的事情:
var res = App.MyModel.find(); //request sent to server
res.abort(); // abort the request before completion
Run Code Online (Sandbox Code Playgroud)
但这不起作用 - 返回的对象是a promise,既没有abort也没有cancel方法.
我正在寻找如何abort在底层XMLHttpRequest对象上调用该方法.
对于那些想知道如何做的人,这里是我实现取消jquery ajax请求的方法.
首先,我在我的Application store中定义了一个新方法,它将在我的自定义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();
}
}
});
Run Code Online (Sandbox Code Playgroud)
在我的自定义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();
}
}
});
Run Code Online (Sandbox Code Playgroud)
现在,您可以cancelQuery在控制器的上下文中调用.
this.store.cancelQuery('yourmodel');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2755 次 |
| 最近记录: |