Как применить несколько функций-замыканий к одному событию?
Как вызвать по событию onclick сразу две функции? По одной все работает, но не могу понять, как же вызвать обе сразу из-под одной внешней функции-обертки?
Смысл в том, что я хочу создать универсальные функции без внешних переменных и чтобы каждая функция выполняла только свою конкретную задачу.
const changeColor = function(){
const colors = ['magenta', 'cyan', 'firebrick', 'springgreen', 'skyblue'];
let currentColor = 0;
return function(){
if(currentColor == colors.length){currentColor = 0};
this.style.background = colors[currentColor++];
}
}
const counter = function(){
let count = 0;
return function(){
this.innerHTML = count;
count++;
}
}
const button = document.querySelector('#button');
button.onclick = function(){
changeColor(); //Как применить эти две функции?
counter();
}
Ответы (1 шт):
Автор решения: Grundy
→ Ссылка
Для добавления нескольких обработчиков можно воспользоваться методом .addEventListener
const changeColor = function() {
const colors = ['magenta', 'cyan', 'firebrick', 'springgreen', 'skyblue'];
let currentColor = 0;
return function() {
if (currentColor == colors.length) {
currentColor = 0
};
this.style.background = colors[currentColor++];
}
}
const counter = function() {
let count = 0;
return function() {
this.innerHTML = count;
count++;
}
}
const button = document.querySelector('#button');
button.addEventListener('click', changeColor());
button.addEventListener('click', counter());
<button id="button">Нажми меня</button>