Accessing global variables from an event listener in Angular: A quick guide

I'm currently working on an Angular project that utilizes fabric.js for canvas functionality. However, I've encountered a problem when trying to use event listeners with the canvas object.

In the snippet of code below, I'm attempting to access the global variable "disabled" within the "movehandler" function. Unfortunately, when I try to log "this.disabled", it returns as "undefined" in the console.

Is there a way to properly utilize global variables within functions for the canvas?

...
disabled = "yes";
...

ngAfterViewInit(){
    this.canvas = new fabric.Canvas(this.canvasTerm);
    console.log(this.canvas);
    this.innerWidth = window.innerWidth;
    this.innerHeight = window.innerHeight;
    this.canvas.setHeight(this.innerHeight - 120);
    this.canvas.setWidth(this.innerWidth - 120);
    this.canvas.on('object:moving', function () {
        console.log('Event object:moving Triggered');
    });

    var moveHandler = function (evt) {
        var movingObject = evt.target;
        //console.log("sss",movingObject.get('left'), movingObject.get('top'));
    };

    //handler for done modifying objects on canvas
    var modifiedHandler = function (evt) {
    var modifiedObject = evt.target;
    console.log(this.disabled);
    console.log( modifiedObject.id,"last",modifiedObject.get('left'), modifiedObject.get('top'));
    };

    var customEvtHandler = function (evt) {
        console.log("I was triggered by a custom event.");
    };

    //or you register with key/value pairs
    this.canvas.on({
        'object:moving' : moveHandler,
        'object:modified' : modifiedHandler,
        'custom:event' : customEvtHandler
    });
  }

Answer №1

Consider using arrow functions.

Instead of:

function (evt) {
}

you can try this:

() => {
}

or

(evt) => {
}

Answer №2

Here's one way to approach it:

let context = this;
let updatedHandler = function (event) {
    let updatedObject = event.target;
    console.log(context.disabled);
};

Alternatively, you can use an arrow function:

let updatedHandler = (event) => {
    let updatedObject = event.target;
    console.log(this.disabled);
};

**Important: Using let is preferred over var for block-specific variables. Reserve var for global scope.

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

Looking to implement pagination and sorting functionalities in multiple Angular Material tables with varying amounts of data?

Adding sorting and pagination to predefined tables is a straightforward process. For example: @ViewChild('myTableSort') myTableSort:MatSort; @ViewChild('myTablePaginator') myTablePaginator:MatPaginator; Once you have the table data, yo ...

Having trouble accessing the dashboard after uploading a document to Firestore

I am currently working on a project where I need to upload an audio file to Firebase storage and also add document data related to the audio file in Firestore database. The process involves recording the audio, uploading it to Firebase storage, submitting ...

Is there a notable reduction in performance due to the use of the second

Is the presence of the second optional chaining causing any negative impact? let flag = somePotentialNullObj?.someNumProp > 0 && somePotentialNullObj?.someOtherProp; The second optional chaining is unnecessary as it works the same without it: ...

Unable to apply the CSS styles on the webpage

I'm having trouble adjusting the CSS for a specific div with the class .cropper inside a component named image-cropper, and I can't figure out why it's not taking effect. Here is an image of the particular div. https://i.sstatic.net/spdJc. ...

Refresh Ionic 2 Platform

I'm currently working on an Ionic 2 app and whenever I make a change to the .ts code, I find myself having to go through a tedious process. This involves removing the platform, adding the Android platform again, and then running the app in Android or ...

Having difficulty converting a list of intricate objects into a CSV format

I am faced with a challenge of handling an array of complex objects, some of which may contain arrays of more objects. My goal is to convert this data into a CSV file. However, whenever there is a list of objects, the information appears as [object Object] ...

Predicate returning negative type assertion

I need help writing two Jest functions that can verify if an object is an instance of a specific type or not. The function expectInstanceOf works perfectly, but unfortunately, the function expectNotInstanceOf is not functioning as expected. export functio ...

Using TypeScript with Watermelondb

I'm currently developing a React App and I want to implement Watermelondb for Offline Storage, but I'm unsure about using it with TypeScript. I have already set up the database and created Course and Lesson model files from the Watermelondb libra ...

What is the reason behind eslint not permitting the rule option @typescript-eslint/consistent-type-imports?

Upon implementing the eslint rule, I configured it like this. module.exports = { rules: { "@typescript-eslint/consistent-type-imports": [ "error", { fixStyle: "inline-type-imports" ...

What is the best way to execute a function while utilizing its default options?

I am working on a project that involves a drop down box and an input box. Here is the HTML code for the drop-down box: <select #select id="id" class="class" (change)="onChange($event)"> <option value="1"> 1 </option> <option v ...

Top tips for creating effective Angular 2 components

My application features a user object that stores and updates all user information using an observable provided by the userService. I am now contemplating the best practice for utilizing this user observable with components. One specific scenario involves ...

Guide to effectively utilizing the ng-bootstrap Typeahead component within a Reactive Form

I've been attempting to implement the ng-bootstrap Typeahead component on a Reactive Form in Angular 2, but despite referencing the example code provided in Typeahead's documentation, I can't seem to get it working. Here is what my current ...

Exploring the world of Storybook Angular and ng-bootstrap

I am facing an issue with creating stories for Angular components that utilize ng-bootstrap. Even though the components work properly, Storybook is giving errors when I try to create stories. For example, when I use the following code snippet: <div id= ...

Modifying column array properties using jsstore

I am working with a jsstore table called tblInvoice const tblInvoice: ITable = { name: "invoice", columns: { // Here "Id" is name of column id: { autoIncrement: true, primaryKey: true, notNull: false }, branchId: { ...

Designing a unique and customized theme for Angular 4

Exploring the world of Angular 4 and Angular Material is an exciting journey for me. Currently, I am delving into the creation of a custom theme in Angular 4. In order to achieve this, we make use of variables to assign colors to primary, accent, and warn ...

What goes on behind the curtain when moving between components in an Angular and Node.js single-page application (SPA)?

I'm struggling to comprehend how the amalgamation of Angular and Node.js can result in a Single Page Application website. My inquiry will be more comprehensible with an illustration: Let's assume I am attempting to construct a SPA website: On t ...

Angular synchronous observables are designed to provide real-time data

API integration is a crucial part of my process for obtaining information. However, the data retrieval can be inconsistent at times; I may receive all the necessary information, only portions of it, or the data might not be in the correct order. getData(s ...

Using forkJoin() to introduce a delay between asynchronous API calls

Here is the code snippet I am currently working with: return forkJoin( pages.map( i => this.http.get(`devices?page=${i}&size=8000`) ) ).subscribe((event: any) => { event.forEach((entry) => { ...

Error: Undefined object trying to access 'vibrate' property

Good day, I apologize for my poor English. I am encountering an issue with Ionic Capacitor while attempting to utilize the Vibration plugin. The documentation lacks detailed information, and when checking the Android Studio terminal, I found the following ...

Positioning customized data on the doughnut chart within chart.js

Is there a way to customize the position of the data displayed in a doughnut chart? Currently, the default setting is that the first item in the data array is placed at 0 degrees. However, I need to place it at a custom position because I am working on a ...