Skip to content

Instantly share code, notes, and snippets.

@rgoytacaz
Last active April 4, 2018 20:16
Show Gist options
  • Save rgoytacaz/82fd49834c20c715cf0e4acdba7edd5b to your computer and use it in GitHub Desktop.
Save rgoytacaz/82fd49834c20c715cf0e4acdba7edd5b to your computer and use it in GitHub Desktop.
(function(){
var categories = [];
var brands = [];
function slugify(text)
{
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\s-]/g, '-') // remove non-word [a-z0-9_], non-whitespace, non-hyphen characters
}
function getSearchQueryString()
{
var url = new URL(document.URL);
return url.search.includes("spec") ? url.search+',b' : '?map=ft,b';
}
function getSearchUrl(searchTerm){
return new URL(document.URL).pathname+'/'+slugify(searchTerm)+getSearchQueryString();
}
function getBrands()
{
/* Departments on page */
$('.search-single-navigator h3').each(function(){categories.push($(this).text())});
var done = categories.length;
/*
* Parallel calls
* This code will never run if there are no categories available on the page.
*/
$(categories).each(function() {
var category = this;
$.ajax({
url: '/api/catalog_system/pub/facets/search/'+category+'?map=c',
headers: {
'Accept':'application/json',
'Content-Type':'application/json'
}
}).done(function (data){
$(data["Brands"]).each(function(){
brands.push(this["Name"])
});
}).error(function () {
/*
* Deal with timeouts/errors or just ignore and continue with what you have
* Most of the time, one category will contain the same brands as other categories.
* Seems like a doable trade-off.
*/
console.log('Timeout/Error occurred. Ignoring...')
}).always(function () {
done -= 1;
if(done ==0) $(document).trigger('brands.ready');
})
});
}
function getBrandTemplate()
{
var uniqBrands = $.unique(brands);
var htmlString = '<h3 class="marca"><span></span><a href="#" title="Marca">Marca</a></h3><ul class="marca">';
$(uniqBrands).each(function(){
htmlString += '<li data-value="'+slugify(this)+'"><a href="'+getSearchUrl(this)+'" title="'+this+'">'+this+'</a></li>';
});
return htmlString += '</ul';
}
function render()
{
$('.search-single-navigator').append(getBrandTemplate());
}
$(document).on("brands.ready",function(){
render();
});
getBrands();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment