JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" class="js-input" placeholder="type something here">
<button class="js-subscribe-p1">Subscribe</button>
<button class="js-unsubscribe-p1">Unsubscribe</button>
<p class="js-paragraph js-p1"></p>
<button class="js-subscribe-p2">Subscribe</button>
<button class="js-unsubscribe-p2">Unsubscribe</button>
<p class="js-paragraph js-p2"></p>
<button class="js-subscribe-p3">Subscribe</button>
<button class="js-unsubscribe-p3">Unsubscribe</button>
<p class="js-paragraph js-p3"></p>
SCSS
* {
margin: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
font-size: 1;
line-height: 2;
padding: 2rem;
background-color: #faf9f9;
}
input {
width: 100%;
display: block;
margin-bottom: 1rem;
font: inherit;
line-height: 3rem;
padding: 0 1rem;
}
button {
font: inherit;
line-height: 2rem;
padding: 0 1rem;
}
p {
margin-bottom: 1rem;
&::before {
opacity: .5;
margin-right: .5rem;
}
&:nth-of-type(1)::before {
content: 'p1: ';
}
&:nth-of-type(2)::before {
content: 'p3: ';
}
&:nth-of-type(3)::before {
content: 'p3: ';
}
}
JavaScript
let observers = [],
data;
const subscribe = f => observers.push(f);
const unsubscribe = f => observers = observers.filter(o => o !== f);
const notify = () => observers.forEach(o => o(data));
for (let i = 1; i <= document.getElementsByClassName('js-paragraph').length; i++) {
let update = text => document.querySelector(`.js-p${i}`).textContent = text;
subscribe(update);
document.querySelector(`.js-subscribe-p${i}`).addEventListener('click', function() {
subscribe(update)
notify();
});
document.querySelector(`.js-unsubscribe-p${i}`).addEventListener('click', function() {
unsubscribe(update)
});
}
document.querySelector('.js-input').addEventListener('keyup', function(e) {
data = e.target.value;
notify();
});