如何在 polymer.dart 中侦听从 parent 传递到 child 的事件

How to listen for event passed from parent to child in polymer.dart

我试图在 Dart 的 Polymer 1.0.0-rc2 中将事件从 parent 传递到 child。问题是我不知道如何去监听 child 中的事件。我试图将 on-control-panel-refire 属性放入 notation_view.html 文件的 dom-module 中,并从那里调用 handle 按钮,但它没有用。监听此事件的正确方法是什么?我知道 on-control-panel-button-pressed 运作良好。

notation_view.dart

@PolymerRegister('notation-view')
class NotationView extends PolymerElement {

  NotationView.created() : super.created();

  @reflectable
  handleButton(Event e, var detail) {
    print("received");
  }
}

main_app.dart

@PolymerRegister('main-app')
class MainApp extends PolymerElement {

  MainApp.created() : super.created();

  @reflectable
  refire(Event e, var detail) {
    querySelector('notation-view').dispatchEvent(new CustomEvent("control-panel-refire",
        detail: {'name' : detail["button-id"]}));
  }

main_app.html

<link rel="import" href="notation_view.html">

<dom-module id="main-app">
  <style>
    :host {
      display: block;
    }
  </style>

  <template>
    <notation-view id="notation-view"></notation-view>
    <control-panel id="control-panel" on-control-panel-button-pressed="refire"></control-panel>
  </template>
</dom-module>

notation_view.html

<dom-module id="notation-view" >
    <style>
        :host {
          display: block;
        }
    </style>

    <template>
        <canvas id="canvas" width="1000" height="1000"></canvas>
    </template>

</dom-module>

我还没有真正尝试过这个,但我认为

   querySelector('notation-view').dispatchEvent(new CustomEvent("control-panel-refire",
    detail: {'name' : detail["button-id"]})); 
   }

应该是

   new PolymerDom(root).querySelector('notation-view').fire("control-panel-refire",
    detail: {'name' : detail["button-id"]}));
   }

如果分析器抱怨未知的 fire() 方法,您可以将 querySelector() 的结果转换为 PolymerElementNotationView

要收听事件,请使用

@PolymerRegister('notation-view')
class NotationView extends PolymerElement {

  NotationView.created() : super.created();

  @reflectable
  handleButton(Event e, var detail) {
    print("received");
  }

  @Listen('control-panel-refire')
  void handleControlPanelRefire(CustomEvent e, [_] /* or `Map detail` instead of [_] */) {
    // handle event
  }

  // alternatively
  EventSubscription _controlPanelRefireSubscr;
  attached() {
    super.attached();
    _controlPanelRefireSubscr = this.on['control-panel-refire'].listen((event) {
      // handle event 
    });
  }

  detached() {
    super.detached();
    _controlPanelRefireSubscr?.cancel();
  }
}