Search code examples
javascriptpolymerweb-component

Cross-DOM observers in Polymer


I have developed a component for i18n in Polymer. Based on <iron-localstorage> it stores and changes the locale.

<iron-localstorage name="marvin-locale-ls"
                           value="{{locale}}"
                           on-iron-localstorage-load-empty="initializeDefaultLocale"
        ></iron-localstorage>
<script>

    MarvinLocaleLS = Polymer({
        is: 'marvin-locale-ls',

        properties: {
            locale: {type: String},
            ...

Also I have a translator component that makes a translation based on this locale. I want to make something like this:

<script>
        Polymer({
            is: 'marvin-translate',
            ls: new MarvinLocaleLS(),
            properties: {
                key: {
                    type: String,
                    notify: true
                },
                locale: {
                    type: Polymer.dom().querySelector('marvin-locale-ls').properties.locale,
                    observer: '_localeObserver'
                }
            },

            ready: function(){
                this.key = this.textContent;
                var t = this.ls.getTranslation(this.key); // get translation from Local Storage
                this.textContent = (t) ? t : this.key; // show translation or key if there is no translation
            },
            _localeObserver: function(){
                console.log('locale changed')
            }

        });


    </script>

In other words I want to create the observer in 'marvin-translate' for a property in 'marvin-locale-ls'. Is it possible?


Solution

  • Take a look at this component, it will enable you to share variable on a Key/Value basis and access them wherever you want. It also supports data-binding (which iron-meta does not yet): https://github.com/akc42/akc-meta