0

ES6 brings a nice module system into Javascript. Modules defined like this:

export default {
   ....
};

Can be easily imported into the source using import myLib from "myModule".

But what if module exports a "constructor" function like this:

export default ( actions ) =>  Reflux.createStore ( {

    state: {
         .....
    },

    config: {
         .....
    },

    init: function() {
        this.listenToMany ( actions );
    },
}

You can import constructor function and then execute it by using

import MyStoreConstructor from "./datastore";
var store = MyStoreConstructor(actions);

Is there any more elegant way to do that?

Vladislav Rastrusny
  • 27,954
  • 23
  • 85
  • 152

1 Answers1

2

You're not really exporting a constructor, it's more of a factory (and should be in lowercase for good style) and I don't think it's getting any slimmer than that. How would the factory know of the actions? Besides modules are only evaluated at most once (at least in every module system I'm aware of) to avoid unwanted side effects - every subsequent request will get a cached version of sorts. You could use a dependency injection library like angularjs has but this is a separate notion than modules.

mfeineis
  • 2,417
  • 17
  • 22
  • Thanks. I just thought, that I can try to turn a store into a ES6 class, provide parametrized constructor to it (to initialize with actions) and export it as a class. What do you think? – Vladislav Rastrusny May 06 '15 at 13:23
  • You could let the datastore depend on the logic that creates your actions and just create exactly one datastore (essentially a singleton) and export this via `import actions from './path/to/actions'; var singletonDatastore = Reflux.createStore(/* use actions */); export default singletonDatastore` - I'm not quite sure about the export syntax but that would give you the same initialized datastore for every request. This violates the dependency inversion principle, though and you lose the ability to create more than one store... but it's doable – mfeineis May 06 '15 at 13:29