在Dart中检测动态复选框/聚合物元素

时间:2015-04-05 19:52:47

标签: dom checkbox dart polymer

Dart的新手没有JS的经验。 我编写了代码来填充JSON的下拉列表。

编辑: 我正在尝试添加聚合物元素。

Polymer .dart

import 'package:polymer/polymer.dart';

@CustomTag('player-item')
class PlayerItem extends PolymerElement{
  @observable String playerName='hello';
  void removePlayer(){
    playerName='';
  }
  PlayerItem.created(): super.created(){}

}

最初是没有定义构造函数的错误。添加空括号 super.created。错误已修复 我究竟做错了什么。如何正确地做到这一点??

polymer.html

playername =动态显示的玩家名称。

现在使用默认字符串。

removeplayer =(想法是)去除整个聚合物元素。

<polymer-element name="player-item">
  <template>
    <input type="image" src="button_minus_red.gif" on-click="{{removePlayer}}">
    <div>{{playerName}}</div>

  </template>

  <script type="application/dart" src="player-item.dart"></script>
</polymer-element>

已编辑的飞镖码: 目标是首先生成选项,然后选择其中一个,如果点击图像(用于此目的的聚合物元素),则随后将其删除。

通过聚合物示例大师。但找不到相关的东西。

需要帮助: 1.我如何动态添加聚合物元素?

  1. 如何将值(即在本例中为播放器的名称)传递给动态添加的 聚合物元素?

  2. 如何去除聚合物元素?

  3. 如何删除通过* .appendedtext添加的附加文本?

  4.     
            import 'dart:html';
    import 'dart:convert' show JSON;
    import 'dart:async' show Future;
    import 'package:polymer/polymer.dart';
    import 'player-item.dart';
    
    //ButtonElement genButton,desButton;
    SelectElement selectTeam;
    FormElement teamPlayer;
    FormElement yourPlayer;
    InputElement teamPlayers;
    
    //final subscriptions = <StreamSubscription>[];
    List<String>teams=[];
    List<String>players=[];
     main() async{
      selectTeam = querySelector('#teamNames');
      teamPlayer = querySelector('#teamPlayers');
      yourPlayer = querySelector('#yourPlayers');
    
      selectTeam.onChange.listen(populateTeams);
      try {
          await prepareTeams1 ();
          selectTeam.disabled = false;  //enable
          //genButton.disabled = false;
        } catch(arrr) {
          print('Error initializing team names: $arrr');
        }
    
     }
    
    void populateYourPlayers(String name){
      querySelector('#yourPlayers').children.add(new Element.tag('player-item'));
                var input = new InputElement();
                input.type = "image";
                input.src = "button_minus_red.gif";
                input.id = name;
                print('yo');
                input.width = 15;
                input.height =15;
                input.appendText(name);
                input.onClick.listen((remove){
                  remove.preventDefault();
                  input.remove();
                  //yourPlayer.children.remove();
                });
                yourPlayer.append(input);
              //  yourPlayer.append(y);
               yourPlayer.appendText(name);
                yourPlayer.appendHtml("<br>");            
                }
    
    void removeYourPlayers(Event e){
    
      yourPlayer.querySelectorAll("input[type=checkbox]").forEach((cb) {
             // print('${cb.checked}');
              if(cb.checked == true){
                print('${cb.id}');
                yourPlayer.children.removeWhere((cb)=>cb.checked==true);
              }
            }
        );
    }
    
    
    Future prepareTeams1()async{
      String path = 'teams.json';
      String jsonString = await HttpRequest.getString(path);
      parseTeamNamesFromJSON(jsonString);
    }
    
    parseTeamNamesFromJSON(String jsonString){
          Map team = JSON.decode(jsonString);
    
          teams = team['Teams'];
              print(teams);     
              for (int i =0; i< teams.length; i++){
                            var option = new OptionElement();
                            option.value = teams[i];
                            option.label =teams[i];
                            option.selected = false;
                            selectTeam.append(option);
                          }
        }
    
    Future prepareTeams2(String Team)async{
      String path = 'teams.json';
      String jsonString = await HttpRequest.getString(path);
      parsePlayerNamesFromJSON(jsonString, Team);
    }
    
    parsePlayerNamesFromJSON(String jsonString,String Team){
          Map team = JSON.decode(jsonString);
          teamPlayer.children.clear();
          teams = team[Team];
              print(teams);
              for (int i =0; i< teams.length; i++){
              var input = new InputElement(type:"image");
            //  input.type = "image";
              input.id = teams[i];
              input.src = "button_plus_green.gif";
              input.width = 15;
              input.height =15;
              input.onClick.listen((p){
                p.preventDefault();
                populateYourPlayers(teams[i]);
              });
             //input.onClick.listen((event){populateYourPlayers(teams[i]);});
              //subscription.cancel();
              teamPlayer.append(input);
              teamPlayer.appendText(teams[i]);
              teamPlayer.appendHtml("<br>");
              }
        }
    
    void populateTeams(Event e){
      print('selectTeam.length: ${selectTeam.length}');
      print(selectTeam.value);
      prepareTeams2(selectTeam.value);
    
      if (selectTeam.length == 0){
    
    }
    
    }
    

    修改HTML:

        <html>
      <head>
        <meta charset="utf-8">
        <title>Pirate badge</title>
        <meta name="viewport"
              content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="piratebadge.css">
        <link rel="import" href="player-item.html">
      </head>
      <body>
        <h1>Team Names</h1>
    
        <select id="teamNames">
    
        </select>
        <h1>Team players</h1>
        <form  id="teamPlayers">
    </form>
    <div>
            <button id="generateButton" disabled>Add Player/Players</button>
          </div>
          <h1>Your players</h1>
        <form  id="yourPlayers">
    </form>
    <player-item></player-item>
    <div>
            <button id="destroyButton" disabled>Remove Player/Players</button>
          </div>
        <script type="application/dart" src="piratebadge.dart"></script>
        <script src="packages/browser/dart.js"></script>
      </body>
    </html>
    

    并根据该选择显示带有复选框的表单。 我面临的问题是如何检测它们已经检查了哪些复选框,如果是,那么如何捕获该复选框的值。

    可能重复 How to know if a checkbox or radio button is checked in Dart?

    但是它们的复选框不是动态创建的。

    如果上述方法有误,请提出建议。

2 个答案:

答案 0 :(得分:1)

您可以阅读checked的{​​{1}}属性

CheckboxInputElement

答案 1 :(得分:1)

根据您想要检测已检查状态的时间,有两种方法。

您可以向提交按钮添加点击处理程序,然后查询复选框。

querySelector("input[type=submit]").onClick.listen((e) {
  querySelectorAll("input[type=checkbox]").forEach((cb) {
    print('${cb.id} {cb.checked}');
  });
});

目前,您为每个复选框分配了相同的ID。这是一个糟糕的选择,因为您无法知道哪个复选框代表哪个项目。

另一种方法是为每个复选框分配一个点击处理程序,以便在单击复选框时立即收到通知。

(我通过使用continuation和forEach而不是for)简化了复选框创建代码。

teams.forEach((team) {
  var input = new InputElement()
    ..type = "checkbox"
    ..id = "player"
    ..onClick.listen((e) {
      print('${cb.id} {cb.checked}');
    });
  teamplayer
    ..append(input)
    ..appendText(team)
    ..appendHtml("<br>");
}

在这种情况下,您可能需要在选择更改时重置点击通知。

import 'dart:async';
// ...
final subscriptions = <StreamSubscription>[];
// ...
subscriptions
  ..forEach((s) => s.cancel())
  ..clear();
teams.forEach((team) {
  var input = new InputElement()
    ..type = "checkbox"
    ..id = "player";
  subscriptions.add(input.onClick.listen((e) {
      print('${cb.id} {cb.checked}');
    }));
  teamplayer
    ..append(input)
    ..appendText(team)
    ..appendHtml("<br>");
}

警告:代码未经过测试,而且我使用了复选框。