Skip to content

Instantly share code, notes, and snippets.

@bennypowers
Created October 3, 2017 21:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennypowers/e9bd90ffed7163c77de8be91ab06765c to your computer and use it in GitHub Desktop.
Save bennypowers/e9bd90ffed7163c77de8be91ab06765c to your computer and use it in GitHub Desktop.
Polymer Singleton Mixin
<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