简体   繁体   中英

ES6 Modules - Global Variables

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM