Jaroslav Tavgen
New Coder
I opened the Developer Tools in Google Chrome, pasted the following code in console and pressed Enter:
Then I pressed some key and the console printed the following:
I should have been called only once
Then I pasted and entered the above-mentioned code ONCE AGAIN. And then pressed some key. Now the console printed the following:
I should have been called only once
I should have been called only once
But why? When I entered the code for the first time it added the event listener "a1". When I entered the code for the second time it should have removed the event listener "a1" and then added the event listener "a1". I.e. there should be ONE event listener. Why are there two?
Code:
document.removeEventListener(`keypress`, a1);
document.addEventListener(`keypress`, a1);
function a1(event){
console.log(`I should have been called only once`);
}
I should have been called only once
Then I pasted and entered the above-mentioned code ONCE AGAIN. And then pressed some key. Now the console printed the following:
I should have been called only once
I should have been called only once
But why? When I entered the code for the first time it added the event listener "a1". When I entered the code for the second time it should have removed the event listener "a1" and then added the event listener "a1". I.e. there should be ONE event listener. Why are there two?