简体   繁体   中英

How can I write to a global variable in Aurelia?

I'm writing an Aurelia application and I have registered an instance of a class inside the aurelia container. Now, when I authenticate a user, that instance has to be modified. How do I modify the original instance from anywhere in my code?

If you want to follow the dependency injection pattern, you need to inject that instance into any class that wants to modify the instance.

import { inject } from 'aurelia-framework'
import { MyClass } from './my-class';

@inject(MyClass)
export class MyViewModel {
    constructor(MyClass) {
        this.myClass = MyClass;
    }
    somethingSpecial() {
        this.myClass.foo = 'bar';
    }
}

How do I modify the original instance from anywhere in my code

Best that put the instance in a module. And then also expose functions that modify the instance. eg

let foo = {}

export function getFoo(){return foo}
export function setFoo(bar){ /* do something */}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM