在我的项目中,我正在迁移到 React,因此不加载 JQuery。由于我不再使用 JQuery,因此对于 AJAX 调用我使用 fetch。使用 JQuery,我可以挂钩 AJAX 调用的开始和结束,因此可以非常轻松地将光标更改为微调器。我在 fetch 中找不到类似的钩子。除了在每个单独的 AJAX 调用中更改它之外,还有其他方法可以做到这一点吗?
很多谷歌搜索一直在寻找关于... JQuery 的答案。
就这样,我认为代码几乎是不言自明的:
// Store a copy of the fetch function
var _oldFetch = fetch;
// Create our new version of the fetch function
window.fetch = function(){
// Create hooks
var fetchStart = new Event( 'fetchStart', { 'view': document, 'bubbles': true, 'cancelable': false } );
var fetchEnd = new Event( 'fetchEnd', { 'view': document, 'bubbles': true, 'cancelable': false } );
// Pass the supplied arguments to the real fetch function
var fetchCall = _oldFetch.apply(this, arguments);
// Trigger the fetchStart event
document.dispatchEvent(fetchStart);
fetchCall.then(function(){
// Trigger the fetchEnd event
document.dispatchEvent(fetchEnd);
}).catch(function(){
// Trigger the fetchEnd event
document.dispatchEvent(fetchEnd);
});
return fetchCall;
};
document.addEventListener('fetchStart', function() {
console.log("Show spinner");
});
document.addEventListener('fetchEnd', function() {
console.log("Hide spinner");
});
这是一个活生生的例子:https://jsfiddle.net/4fxfcp7g/4/ https://jsfiddle.net/4fxfcp7g/4/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)