在道场获得全球处理所有AJAX调用 [英] Getting global handler to all AJAX calls in dojo
问题描述
我需要调用一些常用的方法一个AJAX调用之前和(被称为实际处理方法之前)AJAX调用后的成功。我使用 dojo.aspect
来实现这一目标。
I need to invoke some common methods before an AJAX call is made and after the AJAX call (before the actual handler method is called) is success. I'm using dojo.aspect
to achieve this.
这是我的code样品
function makeAjaxCall(){
dojo.xhrGet({
url:"sample_url",
content:{
test:"value"
},
load:function(response){
//Do some logic here
},
error:function(response){
//handle error
}
});
}
下面是 dojo.aspect
这我用得到一个钩到 XHR
通话。
Below is the dojo.aspect
which I'm using to get a hook to the XHR
calls.
define(["dojo/aspect"], function(aspect){
aspect.after(dojo, "xhr", function(deferred){
console.log("AJAX AFTER");
deferred.then(function(response){
//CALLED AFTER 'load' METHOD IS CALLED.
console.log("Testing");
});
});
aspect.before(dojo, "xhr", function(method, args){
console.log("AJAX BEFORE");
});
});
现在的问题是 deferred.then
在 aspect.after
负荷函数被调用。是否有可能有一个被称为调用实际负载方法之前的方法?
Now the problem is deferred.then
inside aspect.after
is called after the "load
" function is called. Is it possible to have a method which is called before the actual load method is invoked?
推荐答案
简短的回答是肯定的。
首先,有两种方法可以使Dojo的Ajax调用。
First, there are two ways to make ajax calls in Dojo.
-
道场/ XHR
- 这是你有什么上面,这是德precated 赞成 -
道场/请求/ XHR
dojo/xhr
- this is what you have above and this is deprecated in favor ofdojo/request/xhr
第一个实现将调用第二个执行。因此,我建议使用AOP的道场/请求/ XHR
。
The first implementation will call into the second implementation. So I would recommend using aop on dojo/request/xhr
.
aspect.around(require.modules['dojo/request/xhr'], 'result', function(originalXhr){
return function(url, options, returnDeferred){
var dfd = new Deferred();
// Logic before making the xhr call
originalXhr(url, options, returnDeferred)
.then(function(response) {
// Logic handling the response but before resolving the deferred.
dfd.resolve(vm);
// Logic after resolving the deferred.
}, function(err){
// error handling?
dfd.reject(msgs);
}, function(update) {
dfd.progress(update);
});
return dfd;
};
});
您可以找到完整的执行情况 <一href="https://github.com/cswing/evinceframework/blob/master/evf-web-js/src/dojo/evf/serviceRegistry.js" rel="nofollow">https://github.com/cswing/evinceframework/blob/master/evf-web-js/src/dojo/evf/serviceRegistry.js (〜111线)
You can find the complete implementation at https://github.com/cswing/evinceframework/blob/master/evf-web-js/src/dojo/evf/serviceRegistry.js (~ line 111)
用法:
require('dojo/xhr/request', function(xhr){
xhr({...}).then(
function(response) {
//handle response
},
function(error) {
//handle error
}
);
});
在道场/ XHR
code将转化自身上面的使用,所以您发布的code应该工作。
The dojo/xhr
code will translate itself to the usage above, so the code you posted should work.
这篇关于在道场获得全球处理所有AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!