Skip to content
This repository has been archived by the owner on Apr 6, 2022. It is now read-only.

2019 02 17 Injections

Endre Bock edited this page Feb 27, 2019 · 3 revisions

Injections

Yes I know, that is not very common in the JavaScript world. Here you see my roots in PHP and Symfony very clearly.

But the way to inject needed services, manager, etc improves also in the Frontend Application Development alot.

Currently I use a components() function to provide more usable components for the layout:

  /**
   * Enable components for template.
   *
   * @returns {Object}
   */
  get components() {
    return {
      MainMenu:      Menu.Main,
      ThemesManager: Settings.ThemesManager
    };
  }

That the components() function is here, maybe is not so bad. But that we need to provide classes which may will be used, I don't like really.
Also the current usage seems not so nice:

        <this.components.MainMenu lang={this.lang} />

Here we need to passing through the "injection", like the language manager to the menu.

Maybe is would maybe much cooler to have a finish menu to place it, by taking the injected main menu via props:

        {this.props.mainMenu}

In that way, we kick out the responsibility to passing the language manager from the Application.
To take over the "injection", we can simple place in the index.js of the application. That will grow over the time and maybe moved into a extra file.

But the usage seems more or less like follow code:

const languageManager = new LanguageManager();
const mainMenu = <MainMenu lang={languageManager} />;

ReactDOM.render(
  <Application mainMenu={mainMenu} lang={languageManager} />,
  document.getElementById('root')
);

Of course, I need to solve some details, but in general it will decouple even more the Application from the MainMenu and reduce the complexity of the components its self.

By the way:
The Language Manager becomes now a "non-react" class and dummy functions like follow will disappear:

  /**
   * No output of this component.
   *
   * @returns {null}
   */
  render() {
    return null;
  }