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

标签 dart dart-webui polymer

在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/

相关文章:

node.js - (发电机 polymer )哟 polymer 失败,找不到模块 'find-index'

javascript - 使用 querySelector 查找 Polymer 模板内的嵌套元素返回 null

dart - pub全局激活命令-$ HOME/.pub-cache/bin不在路径上

flutter - 如何在flutter中实现用户标记?

process - 有没有一种方法可以在Dart中扩展Web-ui构建过程,以便在构建过程完成后将我的代码复制到其他地方?

dart - WebUI中的base64 img src导致错误

dart - 在 TextInputType 更改后 Controller 重置的 Flutter TextField

dart - 为什么 Dart 的断言方法不起作用?

dart - 在 Polymer.dart 中定义全局过滤器/转换器

javascript - polymer - dom-repeat 内的双向绑定(bind)