Browse Source

4.5: DOM helper functions, default values.

Frederic G. MARAND 5 years ago
parent
commit
a674ca3ef6
2 changed files with 22 additions and 42 deletions
  1. 21 41
      app/app.ts
  2. 1 1
      index.html

+ 21 - 41
app/app.ts

@@ -1,17 +1,30 @@
 function startGame() {
   // Starting a new game.
-  let playerName: string = 'Audrey';
+  let playerName: string | undefined = getInputValue('playername');
   logPlayer(playerName);
 
-  const messagesElement: HTMLElement | null = document.getElementById('messages');
-  // We know messagesElement cannot be null because we control the markup, so
-  // we can use a non-null type assertion
-  const element = messagesElement!;
-  element.innerText = 'Welcome to MultiMath! Starting a new game';
-  console.log('Starting new game');
+  postScore(100, playerName);
 }
 
-function logPlayer(name: string) {
+function getInputValue(elementId: string): string | undefined {
+  // Type assertions applies to the whole document.get...., not to document.
+  // We know that we're only going to pass valid IDs, so will never get a null,
+  // so we can assert the result will always be an input element.
+  const inputElement: HTMLInputElement = <HTMLInputElement>document.getElementById(elementId);
+  if (inputElement.value === '') {
+    return undefined;
+  }
+  else {
+    return inputElement.value;
+  }
+}
+
+function postScore(score: number, playerName: string = 'MultiMath player'): void {
+  let scoreElement: HTMLElement | null = document.getElementById('postedScores');
+  scoreElement!.innerText = `${score} - ${playerName}`;
+}
+
+function logPlayer(name: string = 'MultiMath player'): void {
   console.log(`New game starting for player: ${name}.`);
 }
 
@@ -22,36 +35,3 @@ function arm(doc: HTMLDocument) {
 }
 
 arm(document);
-
-// Type assertions (not casting, more like in Go).
-let value: any = 42;
-let fixedString1: string = (<number>value).toFixed(2);
-let fixedString2: string = (value as number).toFixed(2);
-console.log(value, fixedString1, fixedString2);
-
-/**
- * y is now optional, while x is not.
- */
-function foo(x: number, y?: string): string {
-  return x.constructor.toString() + y;
-}
-
-foo(2, "3");
-foo(2);
-
-function bar(...args: number[]) {
-  console.log(args.reduce((accu: number, curr: number) => accu + curr, 0));
-}
-
-bar(1, 2, 3, 4, 5); // (5+6)/2 = 15
-
-// Rejected because of noImplicitAny.
-// function qux(x, y) { return x + y; }
-// qux('a', 'b');
-
-function sendGreeting(greeting: string = "Hello, world"): void {
-  console.log(greeting);
-}
-
-sendGreeting();
-sendGreeting("Hello, moon");

+ 1 - 1
index.html

@@ -48,7 +48,7 @@
 
         <div class="col-sm-offset-2 col-sm-10" id="score">
             <h2>Scoreboard</h2>
-            <h4>No scores yet</h4>
+            <h4 id="postedScores">No scores yet</h4>
         </div>
 
         <div class="col-sm-offset-2 col-sm-10" id="messages"></div>