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. eg 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.
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'
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.