3

我不仅可以将字符串属性也可以将对象引用传递给事件处理程序吗?

来自https://github.com/sethladd/dart-polymer-dart-examples的 gwt_contacts 示例:

联系人视图.html:

<div id="contact-list">
  <template repeat="{{contacts}}">
    <div>
      <input type="checkbox">
      <span on-click="selectContact" data-id="{{id}}">{{name}}</span>
    </div>
  </template>
</div>

contacts_view.dart 中的处理程序

void selectContact(MouseEvent event, var detail, SpanElement target) {
  String id = target.attributes["data-id"];
  selectedContact = contacts.firstWhere((Contact contact) => contact.id == id);
}

如何传递联系人参考而不是 ID?

类似的问题:如何将任意数据从 Dart 聚合物 Web 组件传递给单击事件处理函数

更改:

在 Christophe Herreman 的暗示下,我添加了一个新元素:

html:

<polymer-element name="contact-view-item">
  <template>
    <span on-click="select">{{contact.name}}</span>
  </template>
</polymer-element>

镖:

@CustomTag("contact-view-item")
class ContactViewItem extends PolymerElement {
  @observable @published Contact contact;

  void select(MouseEvent event, var detail, var target) {
    dispatchEvent(new CustomEvent("contactselected", detail: contact));
  }
}

并将列表更改为:

<div id="contact-list">
  <template repeat="{{contact in contacts}}">
    <div>
      <input type="checkbox">
      <contact-view-item contact="{{contact}}" on-contactselected="contactSelectedHandler"></contact-view-item>
    </div>
  </template>
</div>

并将处理程序添加到 ContactsView:

void contactSelectedHandler(CustomEvent event) {
  selectedContact = event.detail;
}

但是调度自定义事件会抛出错误:

Uncaught Error: unsupported object type for conversion
Exception: unsupported object type for conversion
undefined (undefined:0:0)

连接似乎很好,因为如果我不将联系人作为详细信息传递,则将调用 contactSelectedHandler,但详细信息 - 当然 - 为空。

4

1 回答 1

2

我认为这不可能从 HTML 定义中以声明方式进行。当您从元素类分派对象时,您可以在detaila 的属性中分派对象。CustomEvent请注意,该detail属性实际上只是对event.detailwhen event is a的引用CustomEvent。如果不是,则该detail属性为空。

组件定义

<div id="contact-list">
  <template repeat="{{contacts}}">
    <div>
      <input type="checkbox">
      <span on-click="contact_clickHandler" data-id="{{id}}">{{name}}</span>
    </div>
  </template>
</div>
void contact_clickHandler(MouseEvent event, var detail, SpanElement target) {
  String id = target.attributes["data-id"];
  Contact contact = contacts.firstWhere((Contact c) => c.id == id);
  dispatchEvent(new CustomEvent("contactselected", detail: selectedContact));
}

组件使用

<contact-list on-contactselected="contactList_contactSelectedHandler"></contact-list>
void contactList_contactSelectedHandler(CustomEvent event) {
  var contact = event.detail;
  // do something with selected contact
}
于 2013-10-12T17:33:42.170 回答