gpt4 book ai didi

dart - 如何将任意数据从Dart polymer Web组件传递到Click事件处理函数

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

在Dart的Web UI中,可以响应事件而传递任意数据以起作用,例如,以下代码段响应按钮的on-click事件将值2传递给increment(int incBy)方法:

<!-- Web UI -->
<element name="x-click-counter">
<template>
<button on-click="increment(2)"> <!-- passing a value of 2 -->
Click me
</button>
</template>
</element>
<script>
import 'package:web_ui/web_ui.dart';

class CounterComponent extends WebComponent {
void increment(int incBy) { // accept the value of 2
count = count + incBy;
}
}
</script>

在Polymer(和Polymer.dart)中,单击事件属性需要函数名称的字符串版本,而不是实际的函数调用。这在 polymer docs page上描述为:

The value of an event handler attribute is the string name of a method on the component. Unlike traditional syntax, you cannot put executable code in the attribute.



使用polymer.dart,它看起来像:

<polymer-element name="x-click-counter">
<template>
<button on-click="increment"> <!-- can't pass a value of 2, as you need to pass a string -->
Click Me
</button>
</template>
</polymer-element>
<script>
import 'package:polymer/polymer.dart';

@CustomTag("x-click-counter")
class CounterComponent extends PolymerElement with ObservableMixin {
@observable int count = 0;

void increment(Event event, var detail, var target) { // How do I pass 2 to this function?
count = count ++;
}
}
</script>

问题:如何将任意值传递给 increment函数?

最佳答案

您可以使用html data-属性来传递额外的数据,然后通过target参数访问它们。

重新编写聚合物示例,以添加一个data-incby字段,该字段将值的递增计数如下:

<polymer-element name="x-click-counter">
<template>
<button on-click="increment" data-incby="2"> <!-- now passing the value as a data attribute -->
Click Me
</button>
</template>
</polymer-element>
<script>
import 'package:polymer/polymer.dart';

@CustomTag("x-click-counter")
class CounterComponent extends PolymerElement with ObservableMixin {
@observable int count = 0;

void increment(Event event, var detail, var target) {
int incBy = int.parse(target.attributes['data-incby']); // extract the value 2
count = count + incBy;
}
}
</script>

关于dart - 如何将任意数据从Dart polymer Web组件传递到Click事件处理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18249077/

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