0

A newbie to Dart with no experience in JS. I have written code to populate a dropdown from JSON.

Edit: i am trying to add polymer elements.

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(){}

}

Initially was getting error of constructor not defined. added empty brackets to super.created. error fixed What am i doing wrong. how to do this correctly??

polymer.html

playername = name of player to be displayed dynamically.

right now using default string.

removeplayer = (ideas is to) remove entire polymer element.

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

Edited Dart Code: Objective is first generate options then select one of them and the subsequently remove them if clicked on image(polymer element intended for this purpose).

Went through polymer example master. but couldnt find something related.

Help Needed: 1. how do i dynamically add polymer elements?

  1. how to pass values (ie. in this case name of player) to the dynamically added polymer element?

  2. how to remove polymer elements?

  3. How to remove appended text added via *.appendedtext ?

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

}

}

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

and based on that selection display a form with checkboxes. The issue i am facing is how to detect them which checkboxes have been checked and if so how the value of that checkbox can be captured.

Possible duplicate How to know if a checkbox or radio button is checked in Dart?

However them checkboxes not dynamically created.

If the above approach is wrong, kindly advise.

Community
  • 1
  • 1
Hemant
  • 69
  • 2
  • 10

2 Answers2

1

You can read the checked property of the CheckboxInputElement

    parsePlayerNamesFromJSON(String jsonString,String Team){
      Map team = JSON.decode(jsonString);
      teams = team[Team];
          print(teams);   
          for (int i =0; i< teams.length; i++){
          var input = new CheckboxInputElement();
          input.type = "checkbox";
          input.id = "player";
          input.onChange.listen((_) {
            print("teamplayer ${input.checked}");
          });
          teamPlayer.append(input);
          teamPlayer.appendText(teams[i]);
          teamPlayer.appendHtml("<br>");

    }
GioLaq
  • 2,489
  • 21
  • 26
1

Depending on when you want to detect the checked state there are two ways.

You can add a click handler to the submit button and then query the checkboxes.

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

Currently you are assigning the same id to each checkbox. This is a bad choice because you have no way to know which checkbox represents what item.

Another way is to assign a click handler to each checkbox to get notified immediately when the checkbox is clicked.

(I simplified your checkbox creation code a bit by using continuations and forEach instead of 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>");
}

In this case you might need to reset the click notifications when the selection changes.

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

Caution: code not tested and it's a while I used checkboxes.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thank you sir, i did notice any changes by adding subscriptions, as a result a didnot understand what purpose will it serve. please elaborate on subscriptions and what were you trying to convey (might need to reset the click notifications when the selection changes). where should i use them? New changes made to code. Please advise – Hemant Apr 08 '15 at 17:26
  • I stored the subscriptions to be able to cancel them later. This can prevent memory leaks or might be useful in your logic (to not be notified about clicks anymore without removing the checkboxes). – Günter Zöchbauer Apr 08 '15 at 17:32