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

南楼画角 提交于 2019-12-18 11:53:49

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/19040193/how-do-you-dispatch-and-listen-for-custom-events-in-polymer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!