-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.js
97 lines (84 loc) · 2.72 KB
/
controller.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
var Controller = function() {
// Create the object that we will return.
var that = Object.create(Controller.prototype);
// The <input type="text"> containing the search term.
var searchTermInput;
// The <ul> containing the possible autocompletions.
var resultsList;
// Function to be called on every keyup event
var autocompleteListener;
/**
* Registers a listener function to be called after each keypress.
* The listener will be passed a single String word as an argument
* when invoked.
*
* @param {Function} listener - The function to be called. Function
* must accept a single String as an argument.
*/
that.registerAutocompleteListener = function(listener) {
autocompleteListener = listener;
}
/**
* Appends a String value to the end of the search results list.
*
* @param {String} value - The text to append to the search list.
*/
that.appendToSearchResults = function(value) {
resultsList.appendChild(createListElement(value, onResultClick));
}
/**
* Removes all entries existing in the search results.
*/
that.clearSearchResults = function() {
resultsList.innerHTML = '';
}
/**
* Create an <li> that contains the given value and executes the given
* handler when it is clicked.
*
* @param {String} value - The text to place inside the <li>.
* @param {Function} onClick - The event handler to execute when the <li> is
* clicked.
*/
var createListElement = function(value, onClick) {
var li = document.createElement('li');
li.innerHTML = value;
li.addEventListener('click', onClick, false);
return li;
}
/**
* Handle the click of an autocompletion.
*
* @param {Object} event - The click event.
*/
var onResultClick = function(event) {
searchTermInput.value = event.target.innerHTML;
that.clearSearchResults();
}
/**
* Perform autocompletion each time a key is typed.
*/
var onKeyUp = function() {
that.clearSearchResults();
// If there's a search term and a registered listener,
// invoke the listener with the search term.
var searchTerm = searchTermInput.value
if (searchTerm.length > 0 && autocompleteListener != undefined) {
autocompleteListener(searchTerm);
}
}
// Grab handles to the HTML nodes when the page loads.
var onLoad = function() {
searchTermInput = document.getElementById('search-term-input');
resultsList = document.getElementById('results-list');
searchTermInput.addEventListener('keyup', onKeyUp, false);
}
if (document.readyState != 'loading'){
onLoad();
} else {
document.addEventListener('DOMContentLoaded', onLoad);
}
// Freeze object to prevent modification.
Object.freeze(that);
return that;
};