Skip to content

Commit c2e22e4

Browse files
authored
Merge pull request Laravel-Backpack#5675 from Laravel-Backpack/add-debounce-to-filters
add debounce to filters
2 parents 3e3b279 + 09a22af commit c2e22e4

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

src/resources/views/crud/inc/filters_navbar.blade.php

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ function addOrUpdateUriParameter(uri, parameter, value) {
5353
5454
}
5555
56-
function updateDatatablesOnFilterChange(filterName, filterValue, update_url = false) {
56+
function updateDatatablesOnFilterChange(filterName, filterValue, update_url = false, debounce = 500) {
5757
// behaviour for ajax table
5858
var current_url = crud.table.ajax.url();
5959
var new_url = addOrUpdateUriParameter(current_url, filterName, filterValue);
@@ -68,12 +68,38 @@ function updateDatatablesOnFilterChange(filterName, filterValue, update_url = fa
6868
// and we have a function that will do this update for us after all filters had been cleared.
6969
if(update_url) {
7070
// replace the datatables ajax url with new_url and reload it
71-
crud.table.ajax.url(new_url).load();
71+
callFunctionOnce(function() { refreshDatatablesOnFilterChange(new_url) }, debounce, 'refreshDatatablesOnFilterChange');
7272
}
7373
7474
return new_url;
7575
}
7676
77+
/**
78+
* calls the function func once within the within time window.
79+
* this is a debounce function which actually calls the func as
80+
* opposed to returning a function that would call func.
81+
*
82+
* @param func the function to call
83+
* @param within the time window in milliseconds, defaults to 300
84+
* @param timerId an optional key, defaults to func
85+
*
86+
* FROM: https://stackoverflow.com/questions/27787768/debounce-function-in-jquery
87+
*/
88+
function callFunctionOnce(func, within = 300, timerId = null) {
89+
window.callOnceTimers = window.callOnceTimers || {};
90+
timerId = timerId || func;
91+
if (window.callOnceTimers[timerId]) {
92+
clearTimeout(window.callOnceTimers[timerId]);
93+
}
94+
window.callOnceTimers[timerId] = setTimeout(func, within);
95+
}
96+
97+
function refreshDatatablesOnFilterChange(url)
98+
{
99+
// replace the datatables ajax url with new_url and reload it
100+
crud.table.ajax.url(url).load();
101+
}
102+
77103
78104
function normalizeAmpersand(string) {
79105
return string.replace(/&/g, "&").replace(/amp%3B/g, "");

0 commit comments

Comments
 (0)