【问题标题】:Select element with Dart/Polymer: How to get index on-select使用 Dart/Polymer 选择元素:如何在选择时获取索引
【发布时间】:2014-02-02 18:18:31
【问题描述】:

所以我有以下 Dart/Polymer 类:

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

  @observable int currentIndex = 1;

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

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

和匹配的 html 模板:

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

当我点击选择元素的一个选项时,我会得到正确的索引 - 来自点击之前。 正如w3schools event attributes 告诉我的那样,这是正确的行为,我应该使用 onselect 而不是 onchange 来获取值 after 它已更改。

但是,我找不到 onselect 或 on-select 或类似的东西,当我仅通过 dart 构建选择元素时,onChange.listen 会提供所需的结果(如果不正确)。

我知道我总是可以在按下按钮后检索结果,但在这种情况下,我想在不等待的情况下做一些事情。

我只是错过了正确的关键字吗?

【问题讨论】:

  • 您的 HTML 无效。应该是&lt;polymer-element name="my-select-element"&gt;&lt;template&gt;&lt;select ...&gt;&lt;/select&gt;&lt;/template&gt;&lt;/polymer-element&gt;
  • 您的changed() 必须接受 3 个参数(事件、详细信息、目标)
  • 实际上,我已经 changed() 使用了 0、1 和 2 参数 - 我错过了所有重要的第三个最新元素参数:)

标签: dart dart-polymer


【解决方案1】:

我必须调整 changeEventHandler 方法才能让 JS 版本正常工作:

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

【讨论】:

    【解决方案2】:

    这样我在选择之后得到selectedIndex
    当我尝试绑定到value 以及default value 停止工作(所以我将其注释掉)。

    此示例显示了通知更改的方式:

    • 事件处理程序
    • 可观察属性的更改通知
    <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}');
      }
    }
    

    【讨论】:

    • 是的!在我的情况下,我必须要求处理程序中的 (Select)Element 引用为其 selectedIndex 获取新值。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2023-03-25
    • 2013-08-06
    相关资源
    最近更新 更多