简体   繁体   中英

How to have reactive global variables in polymer 1.0

I followed the documentation at https://www.polymer-project.org/0.5/docs/polymer/polymer.html#global and learnt about the global variables that can be shared across all the instances of a given component. I would like to go a step further. Would like to have the global variable to be reactive. Meaning if its value is changed by one of the instances, it should propagate through all other instances.

<dom-module is="my-writer">
  <template>
    <my-global user="{{username}}"></my-global>
    <button on-click="changeName">Change</button>
  </template>
  <script>
  Polymer({
    is: 'my-writer', 
    changeName: function() { this.username = 'abhilash'; }
  });
  </script>
</dom-module>


<dom-module is="my-reader">
  <template>
    <my-global user="{{username}}"></my-global>
    <span>{{username}}</span>
  </template>
  <script>
  Polymer({
    is: 'my-reader',
    properties: {
      username: { type: String, notify: true, value: 'goje' }
    }
  });
  </script>
</dom-module>

<my-writer></my-writer>
<my-reader></my-reader>

This code would show a button and a span with value as 'goje'. And when I click button, I would want the span to change to show 'abhilash'.

In Polymer 1.0 you may achieve something similar with iron-meta elements. These share the information stored throughout the whole webpage.

https://elements.polymer-project.org/elements/iron-meta

This is half way, the missing part is actually the notification/updating. This actually depends on your implementation i reckon.

Further hints and various implementations can be found here: Polymer 1.0 Global Variables

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM