<button onclick="btnEvent()">Event</button>
<div class="alert border">
This is the alert
</div>
<div class="squares border">
</div>
.squares {
border: solid 1px black;
max-width: 300px;
min-height: 50px;
margin-top: 20px;
}
.square {
border: solid 1px black;
width: 150px;
height: 50px;
margin: 20px auto;
}
.alert {
text-align:center;
max-width: 300px;
min-height: 20px;
margin-top: 20px;
}
/* ************************************** Publish/Subscribe Implementation ************************************** */
const pubsub = (() => {
const events = {};
let subscribersId = -1;
function publish(event, data) {
if (!events[event]) {
return false;
}
const subscribers = events[event];
subscribers.forEach((subscriber) => {
subscriber.func(event, data);
});
return true;
}
function subscribe(event, func) {
if (!events[event]) {
events[event] = [];
}
subscribersId += 1;
const token = subscribersId.toString();
events[event].push({
token,
func,
});
return token;
}
function unsubscribe(token) {
const found = Object.keys(events).some((event) => events[event].some((subscriber, index) => {
const areEqual = subscriber.token === token.toString();
if (areEqual) {
events[event].splice(index, 1);
}
return areEqual;
}));
return found ? token : null;
}
return {
publish,
subscribe,
unsubscribe,
};
})();
/* ************************************** subscribers ************************************** */
function displaySquares(_event, data) {
let squares = '';
Array(data.numberOfSquares).fill(null).forEach(() => {
squares += '<div class="square"></div>';
});
document.querySelector('.squares').innerHTML = squares;
}
function displayAlert(_event, data){
const alert = document.querySelector('.alert');
alert.innerHTML = `The number of squares is: ${data.numberOfSquares}`;
}
/* ************************************** subscribing displayAlert and displaySquares ************************************** */
let displayAlertSubscription = pubsub.subscribe('addSquare', displayAlert);
let displaySquaresSubscription = pubsub.subscribe('addSquare', displaySquares);
/* ************************************** btnEvent ************************************** */
let numberOfSquares = 0;
function btnEvent(){
numberOfSquares += 1;
pubsub.publish('addSquare', { numberOfSquares });
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.