默認情況下,我在「agendaWeek」視圖上顯示了我的日曆。 我使用「事件(作爲函數)」來拉動態事件數據。如何防止在多次單擊「prev」按鈕時運行多個ajax查詢
爲了快速到達一週我想查看,我多次點擊「prev」快速。界面迅速追上,但每次點擊都會觸發ajax請求。這是不理想的,因爲它會縮短響應時間,直到期望的一週,因爲每個干預周的ajax請求都必須處理。
這怎麼能得到緩解?我的想法是,這真是一個功能要求。執行「事件」功能之前,庫應等待300毫秒。
默認情況下,我在「agendaWeek」視圖上顯示了我的日曆。 我使用「事件(作爲函數)」來拉動態事件數據。如何防止在多次單擊「prev」按鈕時運行多個ajax查詢
爲了快速到達一週我想查看,我多次點擊「prev」快速。界面迅速追上,但每次點擊都會觸發ajax請求。這是不理想的,因爲它會縮短響應時間,直到期望的一週,因爲每個干預周的ajax請求都必須處理。
這怎麼能得到緩解?我的想法是,這真是一個功能要求。執行「事件」功能之前,庫應等待300毫秒。
這聽起來像你需要去抖ajaxing功能:
The Debounce technique allow us to "group" multiple sequential calls in a single one.
Here's最新的lodash實現,這是我會用的。
用戶可觀測量它會幫助你解決你的問題 observable
也讀這篇文章 http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html
這個代碼是從上面的鏈接它的真正其角度,但你可以在任何地方使用可觀。
constructor(private wikipediaService: WikipediaService) {
this.term.valueChanges
.debounceTime(400)
.subscribe(term => this.wikipediaService.search(term).then(items => this.items = items));
}
function delayAjax(ajaxCall){
clearTimeout(myFn);
myFn = setTimeout(ajaxCall(), 300)
}
和
<button id="btnNext" onclick="delayAjax(ajaxCall);"><button>
類似的東西...
我可以通過使用eventSources
並返回一個函數數組,每個事件源一個函數來獲得去抖動的功能。 getSources
功能僅僅是爲了方便。在fullCalendar配置,我們將有:
...
eventSources: getSources(),
...
而且功能代碼:
let source1Params = {};
let source2Params = {};
let debouncedSource1 = debounce(
function() {
$.ajax({
url: 'source/1/feed',
dataType: 'json',
data: {
start: source1Params.start,
end: source1Params.end
},
success: function(response) {
// Parse the response into an event list
let eventList = ...
source1Params.callback(eventList);
}
});
}, 200
);
let debouncedSource2 = debounce(
function() {
$.ajax({
url: 'source/2/feed',
dataType: 'json',
data: {
start: source2Params.start,
end: source2Params.end
},
success: function(response) {
// Parse the response into an event list
let eventList = ...
source2Params.callback(eventList);
}
});
}, 200
);
function getSources() {
return [
{
id: 'source1',
events: (start, end, timezone, callback) => {
source1Params = {
'start': start,
'end': end,
'timezone': timezone,
'callback': callback
};
debouncedSource1();
}
},
{
id: 'source2',
events: (start, end, timezone, callback) => {
source2Params = {
'start': start,
'end': end,
'timezone': timezone,
'callback': callback
};
debouncedPlanned();
}
}
];
}
此工程部分,也就是說,如果你點擊下一個或上一個按鈕,連續,它會阻止多個請求,發送只根據需要最後一個。不過這也有多個注意事項:
loading
在配置中的回調將不再起作用。這是因爲loadingLevel
如何在內部實現,它將通過快速點擊而增加,但不會減少,因此永遠不會達到零,從而觸發回調。
我不知道爲什麼這個表決不成,你可以使用observables來解決這類問題。 http://stackoverflow.com/questions/33233881/turn-several-ajax-requests-into-observables-with-rxjs –
至少如果有人需要投票下來,有勇氣說爲什麼! –