How do I pass arbitrary data to a click event handler function from a Dart polymer web component

Chris Buckett picture Chris Buckett · Aug 15, 2013 · Viewed 8.9k times · Source

In Dart's Web UI, it was possible to pass arbitrary data to function in response to events, for example, the following snippet passes the value 2 to the increment(int incBy) method in response to the button's on-click event:

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

In Polymer (and Polymer.dart), the on-click event attribute requires a string version of the function name, rather than an actual function call. This is described on the polymer docs page as:

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.

Using polymer.dart, this looks like:

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

Question: How do I pass an arbitrary value to the increment function?

Answer

Chris Buckett picture Chris Buckett · Aug 15, 2013

You can use html data- attributes to pass extra data, and then access them through the target parameter.

Re-writing the polymer example to add a data-incby field that takes the value increment the count by looks like this:

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