gpt4 book ai didi

dart - 如何将对象引用传递给 dart 聚合物元素内的事件处理程序

转载 作者:行者123 更新时间:2023-12-03 05:44:56 25 4
gpt4 key购买 nike

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

来自 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>

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?

类似问题:How do I pass arbitrary data to a click event handler function from a Dart polymer web component

更改:

根据 Christophe Herreman 的提示,我添加了一个新元素:

html:

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

Dart :

@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。

最佳答案

我认为在 HTML 定义中不可能以声明方式实现这一点。当您从元素类分派(dispatch)对象时,您可以在 CustomEventdetail 属性中分派(dispatch)对象。请注意,当事件是 CustomEvent 时,detail 属性实际上只是对 event.detail 的引用。如果不是,则 detail 属性为 null。

组件定义

<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
}

关于dart - 如何将对象引用传递给 dart 聚合物元素内的事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19335691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com