Transforming JavaScript into TypeScript within an Angular 4 component class

Here is the Javascript code I currently have. I need to convert this into a component class within an Angular component.

As far as I understand, the Character.prototype.placeAt() code is used to add a new method or attribute to an existing object. In this case, the line this.tile = tileTo; within the placeAt() function will update an instance of a Character Object with the global variable tileTo. But how can I translate this into TypeScript?

<script type="text/javascript">
    tileFrom:any = [1, 1];
    tileTo = [1, 1];
    function Character() {
        this.tileFrom = [1, 1];
        this.tileTo = [1, 1];
        this.tile = tileTo;

    }
    Character.prototype.placeAt = function (x, y) {
        this.tileFrom = [x, y];
        this.tileTo = [x, y];
        this.tile = tileTo;
    };
    var player = new Character();
    player.placeAt(..);

</script>

I attempted to convert it like this, but I am unable to utilize Character.prototype in a TypeScript class since it gives the error: 'duplicate identifier Character'. How can I add the placeAt() method to the Character object?

Is it feasible to access class variables without using this or passing an instance of the class? Since this will vary with context, for instance, in the placeAt() method, this refers to the Character object.

export class GametrainComponent implements AfterViewInit {
     tileFrom = [1, 1];
     tileTo = [1, 1];
     Character(self) {
        console.log("ss "+self.tileW)
        this.tileFrom = [1, 1];
        this.tileTo = [1, 1];
        this.tile = self.tileTo;

    };
    Character.prototype.placeAt(x:any, y:any, self) { //error duplicate identifier Character
        this.tileFrom = [x, y];
        this.tileTo = [x, y];
        this.tile = self.tileTo;

    };
    ngAfterViewInit() {
        self = this;
        this.player = new this.Character(self);
        player.placeAt(..);
    }
}

Just keep in mind, I am relatively new to JavaScript and Angular.

Answer №1

In order to create a more organized structure for characters in your game, it is recommended to define a class with specific properties and methods. An example of how this class could be implemented is shown below:

character.model.ts:

export class Character {

  constructor(
    public currentTile: Tile,
    public destinationTile: Tile,
    public tile: Tile
  ) {}

  placeAt(x, y) {
    this.currentTile = [x, y];
    this.destinationTile = [x, y];
    this.tile = this.destinationTile;
  }

}

gametrain.component.ts:

import { Character } from 'file/path';

export class GametrainComponent implements AfterViewInit  {

  player: Character;

  constructor() {}

  ngAfterViewInit() {
      this.player = new Character([1, 1], [1, 1], [1, 1]);
  }

  moveCharacter(tile: Tile) {
    this.player.placeAt(tile);
  }
}

If your characters always start at the same position, you can assign these values within the Character class itself, eliminating the need to pass them when creating a new instance.

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

How to save data to a JSON file using the filesystem module in Node.js

After coming across this helpful guide at , I was intrigued by the creation of a point system in discord.js. The use of let points = JSON.parse(fs.readFileSync("./points.json", "utf8")); to read the file piqued my interest, leading me to explore how to bui ...

Oops! The angular app encountered an error: TypeError - it cannot read property '0' of undefined. Time to debug

Having difficulty grasping the source of an error, as the html side is able to read list[3].main.temp without any issues. However, in the second loop of the generateList function, I encounter an error specifically on $scope.list[i].main.temp, which throws: ...

Tips for customizing the checked color of Material UI Radio buttons

If I want my radio button to be green instead of the default options (default, primary, secondary), how can I achieve that? I attempted to override the color using the classes prop like this: const styles = theme => ({ radio: { colorPrimary: { ...

Tips on invoking a mixin within a Jade template showcased in a Node/Express endpoint

I'm currently developing a component that I plan to use multiple times on a website through a Jade template. This is how my route is set up: router.get('/', function(req, res, next) { res.render('indicators',{category:"", num ...

Is there a way for me to retrieve props that have been passed through the Vue router within a Vue component?

I have configured a route as shown below: { path: 'fit-details', name: 'fit-details', component: Fitment, props: true }, I am passing props via the route using data from the state: this.$router.push({ path: 'fit-details&a ...

Should I fork and customize npm package: Source or Distribution? How to handle the distribution files?

Currently, I am in the process of developing a VueJS web application. Within this project, there is a module that utilizes a wrapper for a JavaScript library obtained through npm and designed to seamlessly integrate with VueJS. However, it doesn't com ...

Is the z-index feature not functioning as anticipated?

I'm currently working on a project involving a book that flips on click on both sides. The process involves checking the direction when a page is clicked and flipping it to the left if it's not to the right. Additionally, I adjust the z-index to ...

jQuery DataTables covering a CSS-anchored menu bar

My webpage has a pinned navigation menu bar at the top and some tables with interactive features using jQuery's DataTables. However, after implementing jQuery, I encountered an issue where the tables cover the menu when scrolling down, making it uncli ...

Troubleshooting issues with ember-data's belongsTo relationship

I am facing an issue with the model I have: Whenever I make a call to this.store.find('history'); A request is sent to http:://www.example.com/api/histories/ and I receive the following JSON response: { "tracks":[ { "id":83, ...

What are some ways to reduce the delay of Dark mode on a website?

Can anyone help me optimize the speed at which dark mode is applied on my website? Currently, there seems to be a delay between page load and the dark mode taking effect. Below is the jQuery.js code I am using: onload = function () { if (localStorage. ...

Storing client-requested data locally

Is it possible to use JavaScript to make an AJAX request to fetch data from a server, then prompt the user to save this data on their computer for later access outside of the browser session? Can this saving functionality be achieved without using a Flas ...

What kinds of data types does MongoDB support in JavaScript?

Regarding the mongodb node client, it allows insertion of JavaScript data using the following syntax: collection.insert({ alpha: 123, bravo: "hello", charlie: [1, 2, 3], }) I am curious to know if mongo supports newer JavaScript data types ...

Issue encountered while setting up controls and AbstractControls in form development

Here is a snippet of code showing how I create and manipulate a form in Angular: this.myForm = new FormGroup({ points: new FormArray([ new FormGroup({ date: this.date, startTime: new FormControl(null, Val ...

Generics in Typescript implemented for a React component that accepts an array of records along with an array of

I am currently working on developing a straightforward typed react component designed to display a table from an array of objects. The input data is structured as follows: // array of records containing data to render in the table data = [ { one: 1, ...

Difficulty maintaining list formatting in AngularJS and Bootstrap due to ng-repeat functionality

I'm currently working on a project where I need to display content from an array using ng-repeat in Angular. The content is originally in JSON format, but it has been stringified before being added to the array. The problem I am facing is that this c ...

Access your own data, shared data, or designated data with Firebase rules

Seeking guidance on implementing firebase rules and queries for Firestore in a Vue.js application. Requirement: User must be authenticated User can read/write their own data entries User can read data with "visibility" field set to "public" User can rea ...

Integrate, Delay, Experimentalize, and Attach components

This inquiry might lean more towards a general browser/javascript discussion rather than a focused prototype question, but I believe this community possesses a deep understanding of javascript and browsers. With that said, here is my query: If the followi ...

The significance of the "? :" operator in JavaScript

These are the lines of code I am currently working with: toggleMore : function( $item, show ) { ( show ) ? $item.find('a.ca-more').show() : $item.find('a.ca-more').hide(); }, Could someone help me understand what this code does? ...

Separate configurations for Webpack (Client and Server) to run an Express app without serving HTML files

I am currently developing an application with a Node Backend and I am trying to bundle it with Webpack. Initially, I had a single Webpack configuration with target: node. However, I encountered issues compiling Websockets into the frontend bundle unless I ...

I'm looking for a method to trigger onChange() specifically on Internet Explorer using only JavaScript, HTML, and CSS without relying on jQuery

Looking for a way to utilize onChange() only on Internet Explorer using Javascript, HTML, CSS (No Jquery). My current code successfully sends the input to my function upon onChange(), but it seems to work smoothly on Chrome and not on IE. Is there a meth ...