I was trying to create a quick pub-sub system based out of localStorage. The process made me realize that my understanding of how ES6 modules work is incomplete.
const subscribers = {};
export default {
subscribe (key, callback) {
if (!Array.isArray(subscribers[key])) {
subscribers[key] = [callback];
} else {
subscribers[key] = [...subscribers[key], callback];
}
},
publish (key, value) {
window.localStorage[key] = value;
subscribers[key].forEach(cb => cb(value));
}
};
I imported this module whenever I wanted to subscribe/publish to a key in localStorage. The problem is that the subscribers object gets reinitialized everytime the module is imported.
Is there a way to do retain the subscribers object without polluting window? I assumed that the import statement will only execute the file once only for the first time it is imported.
Thanks.