Open weikee94 opened 10 months ago
observers.js
const observers = [];
export default Object.freeze({
notify: (data) => observers.forEach((observer) => observer(data)),
subscribe: (func) => observers.push(func),
unsubscribe: (func) => {
[...observers].forEach((observer, index) => {
if (observer === func) {
observers.splice(index, 1);
}
});
},
});
analytics.js
import Observer from './observer';
export function sendToGoogleAnalytics(data) {
console.log('Sent to Google analytics: ', data);
}
export function sendToCustomAnalytics(data) {
console.log('Sent to custom analytics: ', data);
}
export function sendToEmail(data) {
console.log('Sent to email: ', data);
}
Observer.subscribe(sendToGoogleAnalytics);
Observer.subscribe(sendToCustomAnalytics);
Observer.subscribe(sendToEmail);
index.js
import './style.css';
import Observer from './observer.js';
import './analytics.js';
const pinkBtn = document.getElementById('pink-btn');
const blueBtn = document.getElementById('blue-btn');
pinkBtn.addEventListener('click', () => {
const data = '🎀 Click on pink button! 🎀';
Observer.notify(data);
});
blueBtn.addEventListener('click', () => {
const data = '🦋 Click on blue button! 🦋';
Observer.notify(data);
});