Reputation: 129
for some polymer components it is possible to add a listener by setting the name of the listener-function as an attribute of the component. For example:
<iron-signals on-iron-signal-foo="_fooChanged"></iron-signals>
I want to add this functionality to some of my components.
<x-foo on-foo-changed="_fooChanged">
Foo must not be variable like in the iron-signal component. But i have no idea how i execute a function of the host element by its name (as String).
Can anyone give me a hint or an example?
Thank You
Upvotes: 1
Views: 45
Reputation: 5397
It turns out that it was pretty simple, as @Lukasz Mysiak suggested. You just need to fire a custom event with a certain name, like "foo-changed" in your example, and Polymer takes care of calling any method that was registered by adding an on-foo-changed property on the element.
Code I used to test this out:
I have this "parent" element:
This is the parent
<my-child on-correct-value="_handleCorrectValue"></my-child>
</template>
<script>
class MyParent extends Polymer.Element {
static get is() {
return 'my-parent';
}
_handleCorrectValue(event) {
console.log("in parent, got event", event);
}
}
window.customElements.define(MyParent.is, MyParent);
</script>
That uses this child element:
<input on-keyup="_updateValue">
</template>
<script>
class MyChild extends Polymer.Element {
static get is() {
return 'my-child';
}
_updateValue(event) {
if (42 == event.currentTarget.value) {
this.dispatchEvent(new CustomEvent('correct-value', { bubbles: true, composed: true, detail: { value: 42 } }));
}
}
}
(I hope it's pretty obvious I left some parts out to keep the answer short)
And when using the element in a page, every time I type "42" into the input from , the _handleCorrectValue method from the parent is being called.
Reference: https://www.polymer-project.org/2.0/docs/devguide/events
Important: don't forget to set bubbles: true, composed: true on the event!
Upvotes: 1