Skip to content

Instantly share code, notes, and snippets.

@extsalt
Created July 30, 2020 05:54
Show Gist options
  • Save extsalt/85baf4f00b6fb13b250aebbc6538917f to your computer and use it in GitHub Desktop.
Save extsalt/85baf4f00b6fb13b250aebbc6538917f to your computer and use it in GitHub Desktop.
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function markAsLoading() {
$('.js-search-control-container').addClass('loading');
}
function markAsDone() {
$('.js-search-control-container').removeClass('loading');
}
function searchTerm() {
return $('#product-search-input').val();
}
function showResults(results) {
$('.js-search-result-container').html(results);
}
var searchProduct = debounce(function () {
markAsLoading();
fetchProducts(searchTerm()).done(function (res) {
// Exception is there to make sure that if any thing went wrong, always get called always.
try {
showResults(res);
} catch (e) {
console.log(e);
}
}).always(function () {
markAsDone();
});
}, 500);
function fetchProducts(term) {
return $.ajax({
url: '/admin/products/search?q=' + term
});
}
var productSearchInput = document.getElementById('product-search-input');
productSearchInput.addEventListener('input', searchProduct);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment