Polymer 1.0 Global Variables Polymer 1.0 Global Variables javascript javascript

Polymer 1.0 Global Variables


Polymer element <iron-meta> is also an option. For me this was the easiest solution.


I've extended Etherealones' solution to work as a Behavior, and to extend Polymers "set" and "notifyPath" methods to trigger the updates automatically. This is as close as i could get to a true databinding across components/elements:

globals-behavior.html:

<script>var instances = [];var dataGlobal = {};var GlobalsBehaviour = {  properties: {    globals: {      type: Object,      notify: true,      value: dataGlobal    }  },  ready: function() {    var _setOrig = this.set;    var _notifyPathOrig = this.notifyPath;    this.set = function() {      _setOrig.apply(this, arguments);      if (arguments[0].split(".")[0] === "globals") {        this.invokeInstances(_notifyPathOrig, arguments);      }    };    this.notifyPath = function(path, value) {      _notifyPathOrig.apply(this, arguments);      if (arguments[0].split(".")[0] === "globals") {        this.invokeInstances(_notifyPathOrig, arguments);      }    };  },  invokeInstances: function(fn, args) {    var i;    for (i = 0; i < instances.length; i++) {      instance = instances[i];      if (instance !== this) {        fn.apply(instance, args);      }    }  },  attached: function() {    instances.push(this);  },  detached: function() {    var i;    i = instances.indexOf(this);    if (i >= 0) {      instances.splice(i, 1);    }  }};</script>

And in all polymer elements that should have access to the globals variable:

  <script>    Polymer({      is: 'globals-enabled-element',      behaviors: [GlobalsBehaviour]    });  </script>

Examples:

  1. I have posted a full example as a Gist on Github
  2. Here's a snippet to see it in action: