en.javascript.info/02-ui/05-widgets/06-widget-tasks/08-autocomplete/solution/autocomplete-list.js
Ilya Kantor f301cb744d init
2014-10-26 22:10:13 +03:00

62 lines
No EOL
1.3 KiB
JavaScript
Executable file
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

function AutocompleteList(provider) {
var elem;
var filteredResults;
var currentIndex = 0;
this.render = function() {
elem = $('<ol/>');
return elem;
};
this.update = function(value) {
filteredResults = provider.filterByStart(value);
if (filteredResults.length) {
elem.html( '<li>' + filteredResults.join('</li><li>') + '</li>' );
} else {
elem.empty();
}
currentIndex = 0;
renderCurrent();
// это событие, как и всё обновление,
// может быть асинхронным (при получении списка с сервера)
$(this).triggerHandler({
type: 'update',
values: filteredResults
});
};
function renderCurrent() {
elem.children().eq(currentIndex).addClass('selected');
}
function clearCurrent() {
elem.children().eq(currentIndex).removeClass('selected');
}
this.get = function() {
return filteredResults[currentIndex];
};
this.down = function() {
if (currentIndex == filteredResults.length - 1) return;
clearCurrent();
currentIndex++;
renderCurrent();
};
this.up = function() {
if (currentIndex == 0) return;
clearCurrent();
currentIndex--;
renderCurrent();
};
this.clear = function() {
this.update('');
};
}