在es6模块之间共享数据 [英] Sharing data between es6 modules

查看:220
本文介绍了在es6模块之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个es6模块(jspm / system.js& babel)可以彼此共享数据(而不是窗口)的地方:?



Ex:I具有http查询字符串的解析器模块。我在启动时使用它来选择要运行的程序(一个运行许多程序的html文件)。我也在选择的程序中使用它来获取运行它的标志值。示例:三角形或正方形,它们的数量,世界坐标系统等。



如何共享启动模块和各种模块需要标志数据?有没有一个特殊的出口数据空间的模块?



我可以重新解析,没有什么大不了的,但在将来,我可能想要存储的结果长时间的计算,以便它们可以共享。我也可以通过init过程将数据传递给模块,但这可能很尴尬。

解决方案

查看从一个模块传递数据到全局变量,并从另一个模块读取另一个模块,这里是一个简单数据存储模块的示例。



在SimpleStore.js

  var _store = {}; 

class SimpleStore {
构造函数(道具){
if(props){
_store =道具;
}
}
getContent(){
return _store;
}
}
export defualt SimpleStore

和模块A我们将存储一些

 从'./SimpleStore'导入SimpleStore 

class A {
constructor(props){
new SimpleStore({foo:'bar'});在模块B中,
}
}

p>

 从'./SimpleStore'导入SimpleStore 

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

请记住,您可以轻松地更改 _store 在实例化SimpleStore时。 new SimpleStore('替换原始内容')



这就是图书馆喜欢 IMMUTABLE.js 可以使用。另外,请参阅 React Flux Redux


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.

解决方案

If you are looking at passing data to a global var from one module and have the 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 defualt 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

这篇关于在es6模块之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆