Created
October 3, 2017 21:30
-
-
Save bennypowers/e9bd90ffed7163c77de8be91ab06765c to your computer and use it in GitHub Desktop.
Polymer Singleton Mixin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<link rel="import" href="../../bower_components/polymer/polymer-element.html"> | |
<script> | |
/** | |
* @polymer | |
* @mixinFunction | |
* @param {class} superClass | |
* @return {class} | |
* | |
* Polymer.SingletonMixin consumers must be defined with a constructor which | |
* defines this.elements = elements, where elements is a singleton array, such | |
* as within the same closure as the consuming element's class. | |
*/ | |
Polymer.SingletonMixin = (superClass) => { | |
return class extends superClass { | |
static get properties() { | |
return { | |
/** | |
* Collection of connected elements which will receive notifications. | |
*/ | |
elements: { | |
type: Array, | |
}, | |
}; | |
} | |
/** | |
* When an instance of the element instantiates, it adds itself to the | |
* singleton elements array, what for receiving update notifications. | |
*/ | |
connectedCallback() { | |
super.connectedCallback(); | |
this.elements.push(this); | |
} | |
/** | |
* Similarly, when an element is destroyed, it removes itself from the | |
* singleton elements array, what for not causing Ref errors. | |
*/ | |
disconnectedCallback() { | |
super.disconnectedCallback(); | |
this.elements.splice(this.elements.indexOf(this), 1); | |
} | |
/** | |
* This observer propagates any change that polymer's data system is aware | |
* of to all subscribing elements. | |
* | |
* In order to ensure that subscribers are updated, your implementation's | |
* value change observers must accept change objects, not values. | |
* | |
* e.g. | |
* static get observers() { | |
* return [ | |
* 'valueChanged(string.*)', | |
* 'valueChanged(number.*)', | |
* 'valueChanged(object.*)', | |
* ]; | |
* } | |
* | |
* This works with primitives as well as objects and arrays. | |
* | |
* @param {Object} change Polymer change record. | |
*/ | |
valueChanged(change) { | |
this.elements.forEach((element) => { | |
element.set(change.path, change.value); | |
// HACK: set() should handle this. Polymer bug? | |
element.notifyPath(change.path); | |
}); | |
} | |
}; | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment