Paweł Chojnacki
Paweł Chojnacki

Reputation: 15

TypeScript How to access object defined in other class

I have a project that uses Aurelia framework. I want to make global\static object that should be accessed across couple files. But when I try to access it from a different file it says that my object is undefined. Here is what it looks like:

FirstFile.ts

export function showA() {
    console.log("Changed a to " + a);
}
export var a = 3;

export class FirstFile {
    public ModifyA() {
        a = 7;
        showA();
    }

It says that a = 7. Then I use it in other file like this.

SecondFile.ts

import FirstFile = require("src/FirstFile");
export class SecondFile {
    showA_again() {
        FirstFile.showA();
}

I execute showA_again() in my view file called SecondFile.html

<button click.trigger="showA_again()" class="au-target">Button</button>

When I click button, I see in console that variable "a" is still 3. Is there any way to store variables between files?

Upvotes: 0

Views: 3622

Answers (1)

Artiom
Artiom

Reputation: 7837

I'd recommend you to inject FirstFile into SecondFile. Now your code has a smell of bad architecture.

To answer your question: probably you are looking for static (playground sample)

export class FirstFile {

    static showA = function() {
        console.log("Changed a to " + FirstFile.a);
    }

    static a = 3;

    public ModifyA() {
        FirstFile.a = 7;
        FirstFile.showA();
    }
}

export class SecondFile {
    showA_again() {
        FirstFile.showA();
    }
}

Upvotes: 1

Related Questions