Skip to content

Instantly share code, notes, and snippets.

@igorb
Created March 23, 2017 17:26
Show Gist options
  • Select an option

  • Save igorb/599b4a89a0f300de04924c2f5f36e4f0 to your computer and use it in GitHub Desktop.

Select an option

Save igorb/599b4a89a0f300de04924c2f5f36e4f0 to your computer and use it in GitHub Desktop.
Refactored Search JS
$('#search').keyup($.throttle(function() {
// Will only execute 300ms after the last keypress.
if ($('#search').val().length > 0) {
sendSearchAjaxRequest();
} else {
$('.search_dropdown').hide()
}
}, 300));
function sendSearchAjaxRequest() {
$.ajax({
type: 'GET',
url: '/search',
data: {
query: $('#search').val()
},
dataType: 'json',
success: function(response){
$('.search_dropdown').find('.spinner').hide();
new SearchService(response).render();
}
});
}
function SearchService(response) {
this.response = response;
this.container = $('.search_dropdown').find('.results');
}
SearchService.prototype = {
constructor: SearchService,
render: function() {
this.anyResults() ? this.showResults() : this.noResults();
},
anyResults: function() {
this.response.count > 0 // count of records returns from backend
},
noResults: function() {
var $span = $("<span>").text('No results found');
$("<div>").addClass("title").append($span).appendTo(this.container);
},
showResults: function() {
var self = this;
$.each(this.response, function (key, collection) { // each key of json
if (collection.length > 0) {
this.addTitle(key); // css class make first letter uppercase
$.each(collection, function(ignore, item) {
$link = $("<a>").href(item.url).text(item.title); // generate the url & title on backend side
$("<div>").addClass("content").append($link).appendTo(self.container);
});
}
});
},
addTitle: function(title) {
var $span = $("<span>").text(title);
$("<div>").addClass("title").append($span).appendTo(this.container);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment