Playing With DOM And ES5
A quick fun post about "how would you solve this real world problem".
As plus, make each item in the list clickable so that an alert with current text content occur once clicked.
The assumption is that we are in a standard W3C environment with ES5+ support.
If we manage to avoid references we are safer about leaks. If we manage to optimize the procedure, we are also safe about memory consumption over a simplified DOM logic ...
How would you solve this ? Give it a try, then come back for my solution.
Did you solve it the same way ? :)
The Problem
Given a generic array of strings, create an unordered list of items where each item contains the text of the relative array index without creating a singe leak or reference during the whole procedure.As plus, make each item in the list clickable so that an alert with current text content occur once clicked.
The assumption is that we are in a standard W3C environment with ES5+ support.
The Reason
I think is one of the most common tasks in Ajax world. We receive an array with some info, we want to display this info to the user and we want to react once the user interact with the list.If we manage to avoid references we are safer about leaks. If we manage to optimize the procedure, we are also safe about memory consumption over a simplified DOM logic ...
How would you solve this ? Give it a try, then come back for my solution.
The Solution
Here mine:
document.body.appendChild(
/* input */["a","b","c"].map(
function (s, i) {
this.appendChild(
document.createElement("li")
).textContent = s;
return this;
},
document.createElement("ul")
)[0]
).addEventListener(
"click",
function (e) {
if (e.target.nodeName === "LI") {
alert(e.target.textContent);
}
},
false
);
Did you solve it the same way ? :)
Comments
Post a Comment