Skip to content

Instantly share code, notes, and snippets.

@tobiasstrebitzer
Created June 30, 2015 03:24
Show Gist options
  • Save tobiasstrebitzer/1b13fb5180063f7606cd to your computer and use it in GitHub Desktop.
Save tobiasstrebitzer/1b13fb5180063f7606cd to your computer and use it in GitHub Desktop.
Polymer 1.0 Global Variables Behavior
{
"name": "polymer-globals-behavior",
"dependencies": {
"polymer": "Polymer/polymer#~1.0.5"
}
}
<!DOCTYPE html>
<html>
<head>
<title>Globals Behavior Example</title>
<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="globals-enabled-element.html">
</head>
<body>
<template is="dom-bind">
<globals-enabled-element id="element1"></globals-enabled-element>
<globals-enabled-element id="element2"></globals-enabled-element>
</template>
</body>
</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>
<link rel="import" href="globals-behavior.html">
<dom-module id="globals-enabled-element">
<template>
<input type="text" value="{{globals.my_variable::input}}">
</template>
<script>
Polymer({
is: 'globals-enabled-element',
behaviors: [GlobalsBehaviour]
});
</script>
</dom-module>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment