Skip to content

Instantly share code, notes, and snippets.

@andystevensname
Created March 29, 2017 17:44
Show Gist options
  • Save andystevensname/1191b2bddabf387c02bce242e55d4346 to your computer and use it in GitHub Desktop.
Save andystevensname/1191b2bddabf387c02bce242e55d4346 to your computer and use it in GitHub Desktop.
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<dom-module id="asfv-app-data">
<script>
/* https://github.com/auth0-blog/polymer-with-jwt-api/blob/master/src/my-app.html
* http://stackoverflow.com/questions/30849816/polymer-1-0-global-variables
* https://www.sitepoint.com/javascript-design-patterns-singleton/
*/
var storage = (function () {
var instance;
function init() {
return {
set: function(key, data) {
this.keyPairs[key] = data;
},
keyPairs: {},
instances: []
};
};
return {
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
class ASFVAppData extends Polymer.Element {
static get is() { return "asfv-app-data"; }
static get properties() {
return {
data: {
type: Object,
notify: true
},
key: String,
store: Object
}
}
static get observers() {
return [
'_dataChanged(key, data, store)'
]
}
connectedCallback() {
super.connectedCallback();
this.store = storage.getInstance();
this.store.instances.push({key:this.key, instance:this});
}
disconnectedCallback() {
super.disconnectedCallback();
var i = this.store.instances.indexOf({key:this.key, instance:this});
if (i >= 0) {
this.store.instances.splice(i, 1);
}
}
_dataChanged(key, data, store) {
if (store != undefined && key != undefined && data != undefined) {
key = this.key;
if (!key) {
throw('_dataChanged: app-data element requires key');
}
this.store.set(key, data);
for (var i = 0; i < this.store.instances.length; i++) {
if (this.store.instances[i].key == key) {
this.store.instances[i].instance.notifyPath('data', data);
}
}
}
}
};
customElements.define(ASFVAppData.is, ASFVAppData);
</script>
</dom-module>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment