Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. class Searchable {
  2. constructor(items = [], options = {}){
  3. this.version = '0.0.1';
  4. this.controller = options.controller;
  5. this.input = options.input;
  6. this.output = options.output;
  7. this.outputList = this.controller.createElement("UL");
  8. this.items = items;
  9. this.minTermLength = options.minTermLength;
  10. this.events = {
  11.  
  12. };
  13.  
  14. this.outputList.classList.add('searchable-results');
  15. this.output.appendChild(this.outputList);
  16. this.input.addEventListener('keyup', this.search.bind(this));
  17. }
  18.  
  19. search(){
  20. this.outputList.classList.remove('has-results');
  21. this.clearChildElements(this.outputList);
  22. if(this.input.value.length > this.minTermLength){
  23. let regexString = `^${this.input.value.replace(/(\w+)/g, "(?=.*$1)")}.*$`;
  24. let regex = new RegExp(regexString.replace(' ', ''), 'gi');
  25.  
  26. let filteredItems = this.items.filter(function(item){
  27. return regex.test(item.tag);
  28. });
  29. if(filteredItems > 0){
  30. this.outputList.classList.add('has-results');
  31. }
  32.  
  33. this.printResults(filteredItems);
  34. }
  35. return this;
  36. }
  37.  
  38. clearChildElements(parentNode){
  39. while (parentNode.lastChild) {
  40. parentNode.removeChild(parentNode.lastChild);
  41. }
  42. return this;
  43. }
  44.  
  45. printResults(filteredItems){
  46. filteredItems.forEach(function(item){
  47. let listItem = this.controller.createElement("LI");
  48. item.content.tagName ? listItem.appendChild(item.content) : listItem.innerHTML = item.content;
  49. this.outputList.appendChild(listItem);
  50. });
  51. return this;
  52. }
  53.  
  54. add(tag = 'search', content = 'search'){
  55. this.items.push({
  56. tag,
  57. content
  58. });
  59. return this;
  60. }
  61.  
  62. clear(){
  63. this.input.value = '';
  64. this.outputList.remove('has-results');
  65. this.clearChildElements(this.outputList);
  66. }
  67. }
  68.  
  69. window.srchble = new Searchable();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement