Reputation: 716
I have used Polymer 2 to create two custom elements:
i am importing and using them both on another "main element".
What i would like to do is to toggle a class on the "overlay element" with each "button" click.
Is it possible to do this? Can i share data-bindings between elements?
Upvotes: 1
Views: 51
Reputation: 975
Using the adage "events up, props down," sibling elements share data through their parent. There are various solutions for this. I'm using Redux to share data across several elements, but simple parent-to-n-children approach works:
In main-element.html
<button-element id="button"></button-element>
<overlay-element id="overlay"></overlay-element>
...
ready() {
super.ready();
this.$.button.addEventListener('toggle', this._onUpdate);
}
_onUpdate(event) {
this.$.overlay.toggle = !this.$.overlay.toggle;
}
In button-element.html
<button on-click="_doClick">Ok</button>
...
_doClick(event) {
this.dispatchEvent(new CustomEvent('toggle'));
}
In overlay-element.html
<div>[[status]]</div>
...
static get properties() {
return {
toggle: {
type: Boolean,
observer: '_toggleChanged'
},
status: {
type: String
}
...
_toggleChanged(newValue, oldValue) {
this.status = newValue ? 'I\'m hit.' : 'Missed me.';
}
See this pen.
Upvotes: 2