<!-- Module A -->
Name: </br><input type="text" name="name"></br>
Quantity:</br> <input type="number" name="quantity"></br>
<button id="add">Add</button>
<div>Message: <span id="message"></span></div>
<!-- Module B -->
<div>Number: <span id="number"></span></div>
<!-- Module C -->
<div>Total: <span id="total"></span></div>
body {
margin: 0;
padding: 15px;
color: #222;
font: normal normal normal 1rem/1.6 Nunito Sans, Helvetica, Arial, sans-serif;
}
button {
border: none;
color: #fff;
background-color: #34A853;
padding: 15px;
margin-top: 10px;
margin-bottom: 10px;
}
// Implement JavaScript PubSub (Event) Pattern
let Events = (() => {
let events = {};
function on(eventName, fn) {
events[eventName] = events[eventName] || [];
events[eventName].push(fn);
}
function off(eventName, fn) {
if (events[eventName]) {
for (let i = 0; i < events[eventName].length; i++) {
if (events[eventName][i] === fn) {
events[eventName].splice(i, 1);
break;
}
};
}
}
function emit(eventName, data) {
if (events[eventName]) {
events[eventName].forEach((fn) => fn(data));
}
}
return {
on : on,
off: off,
emit : emit
};
})();
// Applying
let ModuleA = (() => {
$("#add").on("click", () => {
let name = $('input[name="name"]').val();
let quantity = $('input[name="quantity"]').val();
$("#message").text(`Adding Item: ${name} - ${quantity}`);
Events.emit("addItem", {
name: name,
quantity: Number.parseInt(quantity)
});
});
})();
let ModuleB = (() => {
Events.on("addItem", onAddingItem);
let maps = {};
let number = 0;
function onAddingItem(data) {
console.log("test", data.name);
if(maps[data.name] == undefined) {
number++;
maps[data.name] = 1;
}
$("#number").text(`${number}`);
}
})();
let ModuleC = (() => {
Events.on("addItem", onAddingItem);
let quantity = 0;
function onAddingItem(data) {
quantity += data.quantity;
$("#total").text(`${quantity}`);
}
})();
This Pen doesn't use any external CSS resources.