0

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.

5
  • As browsers don't currently support modules, what packaging system are you using? Commented Nov 23, 2016 at 15:01
  • Webpack + Babel + ES6 Modules Commented Nov 23, 2016 at 15:05
  • Can you show how you're using it? All imports of that should be sharing the same module state (and do, when I test it in babel-node). Commented Nov 23, 2016 at 15:06
  • @T.J.Crowder - Please refer to my answer below, it was a mistake at my end :-) Commented Nov 23, 2016 at 15:09
  • 1
    Things that turn out to be typos like that are best just deleted. I'm glad you figured it out. Commented Nov 23, 2016 at 15:11

1 Answer 1

1

This is an oversight at my end.

I made a typo when importing this module (capitalization), I specified the wrong filename.

There is another module with an equal name when case is ignored. This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. Rename module if multiple modules are expected or use equal casing if one module is expected.

This caused the module to reinitialize.

Please correct me if I am wrong, but I believe a module will be only executed once for the entire application, when imported for the first time.

Thanks.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.