Следующая демонстрация может связать несколько элементов с любым применимым событием и функцией обратного вызова.Преимущество использования этого класса заключается в том, что параметры selector
, event
и callback
могут быть любыми, и для нескольких слушателей не нужно предпринимать никаких дополнительных шагов.
Демо
Подробности прокомментированы в демо
Это модификация кода, представленного в этой статье .
// Define class
class Homepage {
// Pass a CSS selector
constructor(selector) {
// Reference selector
const elements = document.querySelectorAll(selector);
// Get amount of elements
this.length = elements.length;
// Merge the constructor and elements
Object.assign(this, elements);
}
// Pass a callback function
each(callback) {
// Iterate elements...
for (let node of Array.from(this)) {
// ...call callback function fore each element...
callback.call(node);
}
// ...make the method chainable
return this;
}
// Pass event and callback
bind(event, callback) {
// Iterate constructor...
return this.each(function() {
// ...regiter each element to the event and assign callback
this.addEventListener(event, callback, false);
});
}
};
// Instantiate Homepage class
const likeHate = selector => new Homepage(selector);
// Callback rate()
const rate = e => {
// Reference clicked element
const tgt = e.target;
// If the clicked has .btn class...
if (tgt.matches('.btn')) {
// ...get the clicked value...
const val = e.target.value;
// ...reference article#rate...
const rate = document.getElementById('rate');
// ...assign the value of clicked to [data-rate] of #rate
rate.dataset.rate = val;
// If the value of clicked is 'Superior' = thumbs up/down
let icon = val === 'Superior' ? '?' : '?';
// Assign icon to [data-icon] of #rate
rate.dataset.icon = icon;
}
}
/*
Call the .bind() method on all .btn and register the click event
to each .btn. Assign rate() as callback function.
*/
likeHate('.btn').bind('click', rate);
html,
body {
font: 700 16px/1.3 Raleway;
}
header {
font-size: 1.5rem;
margin: 10px 0;
}
.btn {
border: 0 none transparent;
background: none;
cursor: pointer;
font: inherit;
margin: 0;
}
.btn:hover {
color: blue;
text-decoration: underline;
}
.btn:focus {
outline: none;
}
#rate {
font-size: 1.5rem;
}
#rate::before {
content: attr(data-icon)'\a0';
}
#rate::after {
content: attr(data-rate)'\a0';
}
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
</head>
<body>
<header>
<button class='btn' value='Superior'>Like</button>/<button class='btn' value='Inferior'>Hate</button> the game.
</header>
<article id="rate" data-icon='' data-rate=''></article>
</body>
</html>