search.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. $(function() {
  2. var SearchView = Backbone.View.extend({
  3. events: {
  4. "click #search-clear": "clear"
  5. },
  6. initialize: function() {
  7. this.algolia = algoliasearch("M19DXW5X0Q", "c79b2e61519372a99fa5890db070064c");
  8. this.algoliaHelper = algoliasearchHelper(this.algolia, "font_awesome");
  9. this.template = _.template($("#results-template").html());
  10. this.$searchInput = this.$("#search-input");
  11. this.$searchResultsSection = this.$("#search-results");
  12. this.$searchInputClear = this.$("#search-clear");
  13. this.$iconsSection = this.$("#icons");
  14. this.$searchInput.on("keyup", _.debounce(_.bind(this.search, this), 200));
  15. this.algoliaHelper.on("result", _.bind(this.showResults, this));
  16. },
  17. search: function(event) {
  18. var query = this.$searchInput.val();
  19. if (query !== "") {
  20. this. algoliaHelper.setQuery(query).search();
  21. } else {
  22. this.clearResults();
  23. }
  24. },
  25. clear: function(event) {
  26. event.preventDefault();
  27. this.clearResults();
  28. },
  29. showResults: function(content, state) {
  30. this.$searchResultsSection.html("");
  31. this.$searchResultsSection.removeClass("hide");
  32. this.$searchInputClear.removeClass("hide");
  33. this.$iconsSection.addClass("hide");
  34. var results = [];
  35. _.each(content.hits, function(result) {
  36. results.push(new SearchResultView({ result: result }).render())
  37. });
  38. this.$searchResultsSection.html(this.template({ content: content, results: results.join("") }));
  39. },
  40. clearResults: function() {
  41. this.$searchInput.val("").focus();
  42. this.$searchResultsSection.addClass("hide");
  43. this.$searchResultsSection.html("");
  44. this.$searchInputClear.addClass("hide");
  45. this.$iconsSection.removeClass("hide");
  46. }
  47. });
  48. var SearchResultView = Backbone.View.extend({
  49. initialize: function(options) {
  50. this.template = _.template($("#result-template").html());
  51. this.result = options.result
  52. },
  53. render: function() {
  54. var matches = [];
  55. this.pullMatches(matches, this.result._highlightResult.aliases);
  56. this.pullMatches(matches, this.result._highlightResult.synonyms);
  57. return this.template({ result: this.result, matches: matches });
  58. },
  59. pullMatches: function(matches, list) {
  60. if (list !== undefined) {
  61. _.each(list, function(highlight) {
  62. if (highlight.matchLevel !== "none") {
  63. matches.push(highlight.value)
  64. }
  65. })
  66. }
  67. }
  68. });
  69. var $searchViewElement = $("[data-view=search]");
  70. if ($searchViewElement.length > 0) {
  71. new SearchView({ el: $searchViewElement });
  72. }
  73. });