Dependency injection for Polymer

[ This description is mirrored from README.md at github.com/LssPolymerElements/titanium-dependency-injection on 2019-05-10 ]

titanium-dependency-injection

To install use: bower install --save titanium-dependency-injection

LIVE DEMO AND API

Published on webcomponents.org

Scenario:

---app-main  <-- RESOLVER. anything provided below this (user-manager in this case) is resolved from this component
    --my-parent-component  <-- PROVIDER of user-manager.  user-manager lives in this component.
       -user-manager
       -component-a      
         -component-b
            -component-c
         -component-d
            -component-e
              -my-child-component   <-- needs access to user-manager becomes REQUESTER of user-manager
                -user-manager  
          -component-f
     --my-faq
     --my-feedback

How to use:

In this example we have a single instance component that is called user-manager that we would like to use in a child component nested deep in our app. Rather then binding the user-manager through the component tree in our app, we can simply provide, store, and then request the user-manager as seen below.

1. Declare a parent component as the dependency resolver, which will store the references to provided objects (user-manager)

class MyParentComponent extends TitanumDependencyResolverMixin(Polymer.Element) {

}

2. Provide your component in any child component

class FirstChildComponent extends TitanumProviderMixin(Polymer.Element) {
    ready() {
        super.ready();    
        this.provideInstance("UserManager", this.$.userManager);
    }
}

3. Request your component from any child component

class DemoRequester extends TitaniumRequesterMixin(Polymer.Element) {
    async connectedCallback() {
         super.connectedCallback();
         var userManager = await this.requestInstance('UserManager');
         userManager.ensureLoggedIn();
    }
}

Be both a requester and provider

class MyComponent extends Polymer.mixinBehaviors([TitanumProviderMixin,TitaniumRequesterMixin],Polymer.Element) {
   ready() {
        super.ready();    
        this.provideInstance("MyComponent", this);
   }
   
   async connectedCallback() {
        super.connectedCallback();
        let userManager = await this.requestInstance("UserManager");
        userManager.ensureLoggedIn();
   }
   
   async onLogoutButtonClick(){
        let userManager = this.requestInstance("UserManager");
        userManager.logout();
   }
}

Install

Link to this version
ImportedReleased 30 January 2018MIT License
Framework Support
Polymer 1.0+
Browser Compatibility
Install with
bower install --save LssPolymerElements/titanium-dependency-injection"#3.0.6"
Run the above Bower command in your project folder. If you have any issues installing, please contact the author.
Release notes - Version 3.0.6

Dependencies