Unbinding anonymous functions in JavaScript
Let now an anonymous function is attached to our paragraphs:
let elems = document.querySelectorAll('p');
for (let elem of elems) {
elem.addEventListener('click', function() {
console.log(this.textContent);
});
}
Suppose we want to unbind this function from a paragraph after clicking on this paragraph. However, we are faced with a problem: the function does not have a name, which means we will not be able to refer to it by this name in order to unbind it.
To solve the problem, you need to give the name to the function, making it named functional expression. Let's do it:
let elems = document.querySelectorAll('p');
for (let elem of elems) {
elem.addEventListener('click', function func() { // gives the function name
console.log(this.textContent);
});
}
Now this function can be unbind within itself:
let elems = document.querySelectorAll('p');
for (let elem of elems) {
elem.addEventListener('click', function func() {
console.log(this.textContent);
this.removeEventListener('click', func); // unbinds the function
});
}
Given the list ul
, each item of which
contains a number. Make it so that when you
click on any li
, its number increases
by one.
Modify the previous task so that each li
only increases its value the first time it
is clicked.
Modify the previous task so that each li
increases its value only if its value is less
than 10
.