11

我想要一个子元素来分派一个自定义事件,而父元素来监听它,并采取一些行动。使用 Polymer 时如何执行此操作?

4

1 回答 1

14

您可以像这样从聚合物元素分派自定义事件:

dispatchEvent(new CustomEvent('nameOfEvent'));

然后,父元素可以像这样监听自定义事件:

<child-element on-childspeaks="fireAway"></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>

这是父元素的代码:

<!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>
于 2013-09-26T23:11:40.250 回答