如何从Dart聚合物网页组件传递任意数据到点击事件处理函数

在Dart的Web UI中,可以将任意数据传递到函数以响应事件,例如,以下代码段将值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>

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

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

重新编写聚合物示例以添加一个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>
翻译自:https://stackoverflow.com/questions/18249077/how-do-i-pass-arbitrary-data-to-a-click-event-handler-function-from-a-dart-polym

转载注明原文:如何从Dart聚合物网页组件传递任意数据到点击事件处理函数