11

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?

Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
  • possible duplicate of [How do I fire a custom event from Polymer Dart?](http://stackoverflow.com/questions/18971511/how-do-i-fire-a-custom-event-from-polymer-dart) – Seth Ladd Sep 27 '13 at 22:26

1 Answers1

14

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>
Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51