|
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file |
|
// for details. All rights reserved. Use of this source code is governed by a |
|
// BSD-style license that can be found in the LICENSE file. |
|
|
|
// This app starts out with almost no Dart code, as described |
|
// in Step 1 of the code lab (dartlang.org/codelabs/darrrt/). |
|
import 'dart:html'; |
|
import 'dart:math' show Random; |
|
import 'dart:convert' show JSON; |
|
import 'dart:async' show Future; |
|
|
|
|
|
ButtonElement genButton; |
|
SpanElement badgeElement; |
|
|
|
main() async { |
|
// Your app starts here. |
|
print('program starts...'); |
|
InputElement inputField = querySelector('#inputName'); |
|
inputField.onInput.listen(updateBadge); |
|
|
|
genButton = querySelector('#generateButton'); |
|
genButton.onClick.listen(generateBadge); |
|
|
|
badgeElement = querySelector('#badgeName'); |
|
|
|
try { |
|
print('waiting for pirates data...'); |
|
await Pirate.getPiratesFromRemote(); |
|
print('Received data!'); |
|
|
|
inputField.disabled = false; |
|
genButton.disabled = false; |
|
} catch(error) { |
|
print('Error initializing pirate names: $error'); |
|
badgeElement.text = 'Arrr! No names.'; |
|
} |
|
|
|
} |
|
|
|
void updateBadge(Event e) { |
|
String badgeName = (e.target as InputElement).value; |
|
setBadgeName(new Pirate(firstName: badgeName)); |
|
|
|
if(badgeName.trim().isEmpty) { |
|
genButton..disabled = false |
|
..text = "Aye! Gimme a name!"; |
|
} else { |
|
genButton..disabled = true |
|
..text = "Aye! write yer name!"; |
|
} |
|
} |
|
|
|
void generateBadge(Event e) { |
|
setBadgeName(new Pirate()); |
|
} |
|
|
|
void setBadgeName(Pirate pirate) { |
|
badgeElement.text = pirate.toString(); |
|
} |
|
|
|
class Pirate{ |
|
static final Random randIndex = new Random(); |
|
static List names = []; |
|
static List titles = []; |
|
|
|
static Future getPiratesFromRemote() async { |
|
final String path = 'https://www.dartlang.org/codelabs/darrrt/files/piratenames.json'; |
|
String response = await HttpRequest.getString(path); |
|
_parseResponse(response); |
|
} |
|
|
|
static _parseResponse(String response) { |
|
Map pirateDetails = JSON.decode(response); |
|
names = pirateDetails['names']; |
|
titles = pirateDetails['appellations']; |
|
} |
|
|
|
String _firstName; |
|
String _appellation; |
|
|
|
Pirate({String firstName, String appellation}) { |
|
_firstName = firstName == null ? names[randIndex.nextInt(names.length)] : firstName; |
|
_appellation = appellation == null ? titles[randIndex.nextInt(titles.length)] : appellation; |
|
} |
|
|
|
String get pirateName => _firstName.isEmpty ? '' : '$_firstName the $_appellation'; |
|
|
|
String toString() => pirateName; |
|
} |