How do you dispatch and listen for custom events in Polymer?

Issue

I want a child element to dispatch a custom event and the parent element to listen for it, and take some action. How do I do this when working with Polymer?

Solution

You can dispatch a custom event from a polymer-element like this:

dispatchEvent(new CustomEvent('nameOfEvent'));

Then, parent element can listen for the custom event like this:

<child-element on-childspeaks="fireAway"></child-element>

Here is a more complete example showing how this works. First, here is the code for the child element:

<!DOCTYPE html>

<polymer-element name="child-element">
  <template>
    <div on-click="dispatch">I am a child</div>
  </template>
  <script type="application/dart">
    import 'dart:html';
    import 'package:polymer/polymer.dart';

    @CustomTag('child-element')
    class ChildElement extends PolymerElement with ObservableMixin {

      dispatch(Event e, var detail, Node sender) {
        print('dispatching from child');
        dispatchEvent(new CustomEvent('childspeaks'));
      }
    }
  </script>
</polymer-element>

And here is the code for the parent element:

<!DOCTYPE html>
<link rel="import" href="child_element.html">
<polymer-element name="parent-element">
  <template>
    <div>I am the parent</div>
    <child-element on-childspeaks="fireAway"></child-element>
  </template>
  <script type="application/dart">
    import 'dart:html';
    import 'package:polymer/polymer.dart';

    @CustomTag('parent-element')
    class ParentElement extends PolymerElement with ObservableMixin {

      void fireAway() {
        window.alert('The child spoke, I hear');
      }
    }
  </script>
</polymer-element>

Answered By – Shailen Tuli

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *