Amarok24

event bubbling type-guard

Jan 27th, 2022 (edited)
277
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!--
  2.   HTML, with click events on the <section> and on the <input> element.
  3.   Here the click events are written in Angular, but it doesn't matter, of course. -->
  4. <h1>Event bubbling demo</h1>
  5.  
  6. <section id="wrapper" (click)="onWrapperClick($event)">
  7.  
  8.  <input type="text" (click)="onInputClick($event)" value="click me" />
  9.  
  10. </section>
  11.  
  12. // TS file
  13. class AppComponent
  14. {
  15.  onWrapperClick(event: Event): void
  16.  {
  17.    // When event bubbling occurs this event handler may be called by another event than expected. In this demo the event.target will be either the SECTION or the INPUT element!
  18.    const t = event.target as HTMLElement; // Unsafe, target may be 'null' at runtime!
  19.    console.log('onWrapperClick');
  20.    console.log(`event.target.localName is "${t.localName}"`); // "input" or "section" !!
  21.  }
  22.  
  23.  // That's why it's good to use some kind of a type guard like in this method.
  24.  onInputClick(event: Event): void
  25.  {
  26.    const target: EventTarget | null = event.target;
  27.    let inputElem: HTMLInputElement;
  28.  
  29.    console.log('onInputClick');
  30.  
  31.    if (!target || !(target instanceof HTMLInputElement))
  32.    {
  33.      console.log('event.target is no HTMLInputElement');
  34.      return;
  35.    }
  36.  
  37.    inputElem = target; // Now TypeScript doesn't complain because the type is correct!
  38.  
  39.     console.log(`Target is HTMLInputElement with value "${inputElem.value}"`); // Safe!
  40.     console.log(`event.target.localName "${inputElem.localName}"`); // Always "input".
  41.  
  42.     //event.stopPropagation(); // Stops the event from bubbling, so it won't reach onWrapperClick, that's a direct possibility here.
  43.   }
  44. }
  45.  
  46. // https://github.com/Amarok24
  47.  
RAW Paste Data Copied