Directory

← Back

titanium-dependency-injection

Dependency injection for Polymer

Author

Contributors

Rating

[ 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();
   }
}

Compatibility

(Loading compatibility data...)

Was this helpful? Need more help?
Leave a comment or a question below. You can also join the chat on Discord or ask questions on StackOverflow.

Version

Dependencies

Released
2018-01-30
Maturity
IMPORTED
License
MIT License

Compatibility

Framework
Polymer 1.0+
Browser
Browser Independent
Online