Michael Hopfner
Michael Hopfner

Reputation: 143

Select element with Dart/Polymer: How to get index on-select

So I have the following Dart/Polymer Class:

@CustomTag('my-select-element')
class MySelectElement extends PolymerElement {

  @observable int currentIndex = 1;

  MySelectElement.created() : super.created() {}

  void changed() {
    print(currentIndex);
  }
}

and the matching html template:

<template name="my-select-element">
  <select on-change="{{changed}}" selectedIndex="{{currentIndex}}">
    <option>Index 0</option>
    <option>Index 1</option>
    <option>Index 2</option>
  </select>
</template>

When I click an option of the select element, I get the right index - from the click before. As w3schools event attributes tells me, this is correct behavior and I should use onselect instead of onchange to get the value after it has changed.

However, I can't find onselect or on-select or anything like it, and when I build the select element via dart alone, onChange.listen delivers the desired, if incorrect, result.

I know I could always retrieve the result after a button has been pressed, but in this scenario, I want to do stuff without waiting.

Am I just missing the right keyword?

Upvotes: 2

Views: 1722

Answers (2)

bey
bey

Reputation: 161

I had to adapt the changeEventHandler method to get the JS version to work properly:

void changeEventHandler(Event e, var details, var target) {
    /* Fix JS bug - ${currentIndex} still refers to the old value whereas in Chrome it already has the new value */
    currentIndex = target.selectedIndex;
}

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658263

This way I get the selectedIndex after the selection.
When I tried to bind to value as well the default value stopped working (so I commented it out).

This example shows to ways to be notified about changes:

  • event handler
  • change notification of observable property
<polymer-element name="my-select" >
  <template>
    <select selectedIndex="{{currentIndex}}" on-change="{{changedHandler}}">
      <option>Index 0</option>
      <option>Index 1</option>
      <option>Index 2</option>
    </select>

    <!-- <div>value: {{value}}</div> -->
    <div>currentIndex: {{currentIndex}}</div>
  </template>
  <script type='application/dart' src='my_select.dart'></script>
</polymer-element>
library x;

//import 'dart:async';
import 'dart:html';
import 'package:polymer/polymer.dart';

@CustomTag('my-select')
class MySelect extends PolymerElement {
  @observable int currentIndex = 1;
  @observable int value = 1;

  MySelect.created() : super.created() {
    print('MySelect');
  }

  void changedHandler(event, details, Element target) {
    print('changed: ${currentIndex}');
  }

  void currentIndexChanged(old) {
    print('currentIndexChange: ${currentIndex}');
  }
}

Upvotes: 1

Related Questions