从另一个类的构造函数调用变量

时间:2018-04-18 12:53:07

标签: javascript class variables call aurelia

假设我有一个.js文件,其中导出了类,构造函数是这样构建的:

 constructor(info) {

    this.info = info;
}

在另一个.js文件中,我想调用该变量并对其进行更改,我希望更改能够反映在变量来源的原始.js文件中,因此我很好地导入了类并注入了它: / p>

@inject(ContactGateway, Router, TestElement)
export class LoginNormal {
  constructor(contactGateway, router, testelement) {
    this.contactGateway = contactGateway;
    this.router = router;
    this.testelement = testelement;
  }

然后在同一个.js文件中,在函数内部,我更改了原始变量:

  TestInfo() {
    let testinfo = this.testelement;
    testinfo.info= true;
  }

经过进一步测试,我发现原始变量根本没有被改变,在尝试通过另一个文件中的函数改变原始变量的布尔值时,我做错了什么?

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可能只是注入了TestElement的不同实例。自定义元素通常作用于特定的子容器或视图(取决于上下文)。

如果您想确保在任何地方获得相同的实例,并且您确定只需要一个实例,那么您可以手动将该自定义元素的类注册为单个实例。根容器。

虽然只需要一个单独的服务/州级类,然后保留info属性,这样会更好。将该状态类注册为根容器上的单例/实例,并将其注入TestElementLoginNormal类。这是传递信息以便在不同的html资源之间进行读取/修改的推荐方法。

这样的事情通常应该起作用(相应地拆分/移动/重命名):

@inject(ApplicationState)
export class TestElement {
    constructor(state) {
        this.state = state;
    }
}

@inject(ContactGateway, Router, ApplicationState)
export class LoginNormal {
    constructor(contactGateway, router, state) {
        this.contactGateway = contactGateway;
        this.router = router;
        this.state = state;
    }

    TestInfo() {
        this.state.info = true; // will be changed in your TestElement too
    }
}

// the hard way
export class ApplicationState {
    constructor(info) {
        this.info = info;
    }
}

export function configure(config) {
    config.instance(ApplicationState, new ApplicationState(false))
}

// or the easy way (no configure required, but needs parameterless constructor)
@singleton()
export class ApplicationState {
    constructor() {
        this.info = false;
    }
}
相关问题