[quote=āPaulOB, post:14, topic:236630ā]Yeah, I had that at first, but I heard that God (aka D. Crockford) doesnāt use this
, so for fun I also like to see if I can do without it. 
[/quote]
Nice one. The way to do without the this keyword in the click event handler, is to get the event target instead. For example:
var links = document.querySelectorAll('.connect a');
for (var i = 0; i < links.length; i++) {
window.addEventListener.call(
links[i],
'click',
function(evt) {
var link = evt.target;
console.log(link.className);
evt.preventDefault();
},
false
);
}
Although, that Array.from technique is certainly the most pleasing of all those seen here thus far:
function clickLinkHandler(evt) {
var link = evt.target;
console.log(link.className);
evt.preventDefault();
}
var links = document.querySelectorAll('.connect a');
Array.from(links).forEach(function(link) {
link.addEventListener("click", clickLinkHandler, false);
});
I can only think of one thing better than that, and that is to not place a handler on each link, but to sit and watch from the connect element instead:
function connectHandler(evt) {
var link = evt.target;
if (link.nodeName !== "A") {
return;
}
console.log(link.className);
evt.preventDefault();
}
var connect = document.querySelector('.connect');
connect.addEventListener("click", connectHandler, false);
Itās a toss-up whether to do an early exit if itās not a link, or place the code within an if statement. I prefer to go with the guard clause, as it tends to result in less indented and easier to follow code. The other option though is given below.
function connectHandler(evt) {
var link = evt.target;
if (link.nodeName === "A") {
console.log(link.className);
evt.preventDefault();
}
}
var connect = document.querySelector('.connect');
connect.addEventListener("click", connectHandler, false);