Enhancing EventTarget in TypeScript (Angular 2+) for ES5 compilation

Is there a way to create a custom class that extends the EventTarget DOM API class?

Let's say we have the following class:

class MyClass extends EventTarget {        

  constructor() {
    super();
  }

  private triggerEvent() {
    this.dispatchEvent(new Event('someEvent'));
  }

}

However, upon instantiation, an error is encountered:

  • ERROR TypeError: Failed to construct 'EventTarget': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

This issue seems to stem from the requirement of proper ES2015 classes for this API to function, whereas code transpilation is done at the ES5 level.

If attempting to use the following constructor instead:

constructor() {
  Reflect.construct(EventTarget, [], MyClass);
}

A new error arises when trying to invoke addEventListener():

  • ERROR TypeError: Illegal invocation
    .

In addition, a TypeScript compilation error occurs:

  • error TS2377: Constructors for derived classes must contain a 'super' call.
    .

Answer №1

To simplify the solution, one approach could be to implement the EventTarget interface but delegate the actual implementation to an existing class such as DocumentFragment.

Another option is to extract this functionality into a reusable class:

export class DelegatedEventTarget implements EventTarget {

  private delegate = document.createDocumentFragment();

  addEventListener(...args: any): void {
    this.delegate.addEventListener.apply(this.delegate, args);
  }

  dispatchEvent(...args: any): boolean {
    return this.delegate.dispatchEvent.apply(this.delegate, args);
  }

  removeEventListener(...args: any): void {
    return this.delegate.removeEventListener.apply(this.delegate, args);
  }

}

Then, this new class can serve as a parent for our original class:

class MyClass extends DelegatedEventTarget {

  private triggerEvent() {
    this.dispatchEvent(new Event('someEvent'));
  }

}

Using this method will maintain typings and ensure compatibility when compiling down to ES5.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a debounced and chunked asynchronous queue system that utilizes streams

As someone who is new to the concept of reactive programming, I find myself wondering if there exists a more elegant approach for creating a debounced chunked async queue. But what exactly is a debounced chunked async queue? While the name might need some ...

Encountered a problem while installing an npm package for Angular 2

I seem to be encountering an error when trying to run the npm install command in the command prompt behind my corporate proxy firewall. Previously, I was able to edit the npm file with the proxy settings, but now I receive this error no matter what npm com ...

Moving the layout container towards the left: a quick guide

I am currently attempting to display the legend contents in a horizontal alignment within the layout container. The issue is that while the layout containing the legend aligns horizontally as desired, it extends beyond the screen border. I do not want the ...

Re-evaluating information when the query parameter is modified?

While working on my angular 2 projects, I encountered an issue where I couldn't reload the page by changing the query parameters within the same URL. I am currently utilizing resolve to fetch data before loading the page. I am now striving to figure ...

Dealing with the endless looping problem in Next.js caused by useEffect

Looking to implement a preloader that spins while the content is loading and disappears once the loading is complete. However, encountering an issue where the site gets stuck on the loading page and keeps loading infinitely. I've tried multiple soluti ...

Apollo-Server presents errors in a polished manner

It seems like the question explains itself adequately. I am currently using 'apollo-server-core' version 3.6.5 Desired Errors: { "errors": [ { "message": "Syntax Error: Unexpected < ...

[Heroku][Angular] Dealing with "Template parse errors" upon deploying my application

Encountered errors while deploying my application using "express" on Heroku: Uncaught Error: Template parse errors: Unexpected closing tag "button". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR ...

Awaiting a response from the http.get() function

Currently, I am in the process of creating a login feature using Angular and Ionic 2. This feature aims to verify if the user is registered in the database through a PHP server and return a user ID. However, I have encountered an issue with the asynchronou ...

Issues with loading Angular 4 Bootstrap JS post compiling

Utilizing normal bootstrap 3 within an Angular 4 application has been working well when compiling for development using ng serve. However, upon building the application with ng build, I encounter an issue where my bootstrap.js fails to load. Below are th ...

Is there a way to organize this array based on the group score?

0: {id: 2575, groepName: "ezeez-1", groupScore: 50, Players: Array(0)} 1: {id: 2574, groepName: "ezeez-2", groupScore: 25, Players: Array(0)} 2: {id: 2576, groepName: "ezeez-3", groupScore: 10, Players: Array(0)} 3: {id: 2577, ...

Identifying modifications within the @Input property in Angular 4

Can someone clarify how to detect changes in an @Input property within a component, rather than just when passed from its parent? I haven't found a clear answer to this yet. Thank you! ...

How can I obtain the rowIndex of an expanded row in Primeng?

<p-dataTable [value]="services" [paginator]="true" expandableRows="true" rowExpandMode="single"> ...</p-dataTable> There is a similar example below: <ng-template let-col let-period="rowData" let-ri="rowIndex" pTemplate="body">...</ ...

The concept of Typescript involves taking a particular type and generating a union type within a generic interface

Picture a straightforward CollectionStore that contains methods for creating and updating a record. The create() method takes in a set of attributes and returns the same set with an added id property. On the other hand, the update method requires the set t ...

How to efficiently retrieve automatically generated elements by ID in Angular 2

In order to create a 6x6 grid, I am using the following code: <ion-grid> <ion-row *ngFor="let rowIndex of createRange(6)" [attr.id]="'row-'+rowIndex"> <ion-col col-2 *ngFor="let colIndex of createRange(6)" [attr.id]= ...

`Running ng serve will result in the creation of a 'dist' folder within each app sub

Since beginning my project, I have encountered an issue that is both normal and frustrating. The dist folder is being created with incomplete information related to the components inside it. dashboard dist (unwanted) components panel dist (unwanted) c ...

Angular 2, the change event is not triggering when a bootstrap checkbox is clicked

Encountering an issue, the (change) function is not triggering in a specific checkbox. <input [(ngModel)]="driver.glasses" name="glasses" type="checkbox" class="make-switch" (change)="changeFunction()" data-on-color="primary" data-off-color="info"&g ...

Experiencing a 404 error while attempting to revoke access token using Google OAuth2 revoke endpoint

Using angularx-social-login for user authentication via Google. The token retrieval process looks like this: https://accounts.google.com/o/oauth2/iframerpc?action=issueToken&response_type=token%20id_token&login_hint=LOGIN_HINT&client_id=CLIEN ...

Dividing an array into categories with typescript/javascript

Here is the initial structure I have: products = [ { 'id': 1 'name: 'test' }, { 'id': 2 'name: 'test' }, { 'id' ...

Elastic Beanstalk hosted apps do not support the transmission of large files

I've been working on a web application that requires storing large files, specifically mp4 videos with sizes sometimes exceeding 100mb. However, I encountered an error when trying to upload these files from a static Angular website hosted in an S3 buc ...

Utilizing Async Storage for Language Localization

Currently, I am utilizing two separate APIs for localization, both of which return JSON data. getEnLoc() //400kb getEsLoc() //400kb My plan is to call these APIs in App.ts during the app's initialization phase and store the retrieved JSON objects in ...