Sharing data between es6 modules

拈花ヽ惹草 提交于 2019-12-13 16:51:35

问题


Is there a place where es6 modules (jspm/system.js & babel) can share data with each other (not window):?

Ex: I have a parser module for http query strings. I use it at startup to choose which program to run (one html file running many programs). I also use it in the selected program to get flag values for running it. Example: triangles or squares, what number of them, world coord system ... etc.

How do I share the result of the query string parse between the startup module and the various modules needing the flag data? Is there a special "exports" data space for modules?

I can just re-parse, no big deal, but in the future, I may want to store results of long computations so they can be shared. I can also pass the data to the modules in an "init" procedure, but this can be awkward.


回答1:


If you are looking at passing data to a global var from one module and having another module read from it here's an example of a simple data store module.

in SimpleStore.js

var _store = {};

class SimpleStore {
   constructor(props) {
      if (props) { 
         _store = props;
      }
    }
    getContent() {
        return _store;
    }
}
export default SimpleStore

and in Module A we'll store something

import SimpleStore from './SimpleStore'

class A {
    constructor(props) {
        new SimpleStore({foo: 'bar'});
    }
}

in Module B we'll get that content

import SimpleStore from './SimpleStore'

class B {
    constructor(props) {
        var content = new SimpleStore().getContent();
    }
}

Keep in mind you can easily change the content of _store when instantiating SimpleStore ie. new SimpleStore('replace the original content')

That's where libraries like IMMUTABLE.js can be useful. Also as example check out the store modules used with React Flux and Redux




回答2:


You should make a 3rd "config" module, say "C", so that "A" and "B" both depend on it. This module loads/caches/exposes the configuration data to the other modules.



来源:https://stackoverflow.com/questions/30956636/sharing-data-between-es6-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!