0
votes

I'm trying to replicate the example in the following section of the Polymer 0.5 docs, which uses the MonoState pattern to implement global variables in Polymer:

http://www.polymer-project.org/0.5/docs/polymer/polymer.html#global

I'm trying to get this working using Polymer 1.0 but am not having much luck.

Here is my code for the app-globals and my-component custom elements. It's the same as in the above link apart from the slightly different syntax in Polymer 1.0. e.g. using dom-module instead of polymer-element.

<dom-module name="app-globals">
    <script>
        (function() {
            // these variables are shared by all instances of app-globals
            var values = {
                firstName: 'John',
                lastName: 'Smith'
            }

            Polymer({
                 is: 'app-globals',
                ready: function() {
                    // make global values available on instance.
                    this.values = values;
                }
            });
        })();
    </script>
</dom-module>

<dom-module name="my-component">
    <template>
        <app-globals id="globals"></app-globals>
        <div id="firstname">{{$.globals.values.firstName}}</div>
        <div id="lastname">{{$.globals.values.lastName}}</div>
    </template>
    <script>
        Polymer({
             is: 'my-component',
              ready: function() {
                console.log('Last name: ' + this.$.globals.values.lastName);
              }
    });
    </script>
</dom-module>

The usage is simply:

<my-component></my-component>

Initially I was encountering the error "Cannot read property '$' of undefined". So I replaced the div content $.globals.values.firstName with this.$.globals.values.firstName (and similarly for the lastName field) in the my-component custom element.

However the divs are not displaying the first and last names. It looks like this.$.globals.values.firstName and this.$.globals.values.lastName are not set when the div's are rendered.

Would appreciate some help to resolve this.

1
Have you tried this.set('values', values); instead of this.values = values;? Does console.log() print the values? Also have a look at elements.polymer-project.org/elements/iron-meta that does what your element is supposed to do. - Günter Zöchbauer
@GünterZöchbauer I wasn't aware of the iron-meta element. I'll look into it, thanks! - aw1975
I'm pretty sure it's <dom-module id="app-globals"> I think you can catch these errors if you use polylint (github.com/PolymerLabs/polylint) - Cristian

1 Answers

3
votes

Here is working example, Plunk

properties: {
          values: {
            type: Object,
            notify: true
          }
        },

        ready: function() {
          // make global values available on instance.
          this.values = {
            firstName: 'John',
            lastName: 'Smith'
          }
        }