我是否可以不仅传递String属性,还能传递对象引用到事件处理程序?
来自https://github.com/sethladd/dart-polymer-dart-examples的示例gwt_contacts:
contacts_view.html:
<div id="contact-list">
<template repeat="{{contacts}}">
<div>
<input type="checkbox">
<span on-click="selectContact" data-id="{{id}}">{{name}}</span>
</div>
</template>
</div>
contact_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?
类似的问题:How do I pass arbitrary data to a click event handler function from a Dart polymer web component
CHANGED:
在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,但是详细信息当然是null。
答案 0 :(得分:2)
我认为这不可能在HTML定义中以声明方式进行。当您从元素类中调度对象时,可以在detail
的{{1}}属性中调度对象。请注意,CustomEvent
属性实际上只是当事件为detail
时对event.detail
的引用。如果不是,则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>