let typingTimer;
//Detect keyup focusin, focusout and keydown events on the search input and
//handle them.
$searchInput.on('keyup focusin focusout keydown', (keyPressed) => {
//Restart the search timer on each event so the server doesnt get
//spammed with multiple requests at a time.
clearTimeout(typingTimer);
if (event.type == 'keyup' && $searchInput.val() && keyPressed.keyCode >= 65 && keyPressed.keyCode <= 90) {
//Execute search after certain amount of time.
typingTimer = setTimeout(searchFunction, debounceTime);
} else if (!$searchInput.val()) {
//Empty the search list if user erases everything in the input.
$searchChampList.empty();
} else if (event.type == 'focus') {
//Show the search list if the user clicks on the search input.
$searchChampList.fadeIn(300);
} else if (event.type == 'blur') {
//Hide the search list if the user clicks out of the search input.
$searchChampList.fadeOut(300);
} else if (event.type == 'keydown' && $searchInput.val() && keyPressed.keyCode == 40) {
//Navigate the search list with down arrow and enter the champs name into the input for feedback.
$('.search__champ-list-item_highlighted').next().addClass("search__champ-list-item_highlighted");
$('.search__champ-list-item_highlighted').prev().removeClass("search__champ-list-item_highlighted");
$searchInput.val() == $('.search__champ-list-item_highlighted.search__champ-name').text();
} else if (event.type == 'keydown' && $searchInput.val() && keyPressed.keyCode == 38) {
//Same as above but with up arrow.
$('.search__champ-list-item_highlighted').prev().addClass("search__champ-list-item_highlighted");
$('.search__champ-list-item_highlighted').next().removeClass("search__champ-list-item_highlighted");
$searchInput.val() == $('.search__champ-list-item_highlighted.search__champ-name').text();
} else if (event.type == 'keydown' && $searchChampList.children().length >= 1 && keyPressed.keyCode == 13) {
//Pressing enter goes to the highlighted champs page.
window.location.href = $('.search__champ-list-item_highlighted').attr('href');
}
});
它看起来有点乱,难以阅读IMO,唯一使用所有4个事件的表达式是clearTimeout(typingTimer)
。在这种情况下,将它们分解为单独的事件方法是一种更好的做法吗?
$searchInput.event((handler){
//code
})
答案 0 :(得分:4)
我建议你分开它。在这种情况下,您将所有内容放在一个包含许多ifs的大函数中,这不容易阅读(这也使代码难以维护)。当调用任何事件时,您将执行所有验证,然后执行一段简单的代码。
这是一件很简单的事情,但如果您仍然对所有代码执行相同的操作,您将真正开始看到问题。
此外,如果您使用的是jQuery,它会确保处理程序按照定义的顺序触发,因此您可以先为所有事件定义clearTimeout,然后编写特定的回调。