【问题标题】:Call Variable from Constructor of Another Class从另一个类的构造函数调用变量
【发布时间】:2018-09-28 17:28:39
【问题描述】:

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

 constructor(info) {

    this.info = info;
}

在另一个 .js 文件上,我想调用该变量并对其进行更改,并且我希望将更改反映在该变量来自的原始 .js 文件中,因此我很好地导入了该类并将其注入:

@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;
  }

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

提前致谢。

【问题讨论】:

  • 您是否尝试过直接更新它而不是先创建let testinfothis.testelement.info = true
  • 您的代码中遗漏了许多部分。最关键的是logininfocustomelement 是在哪里定义的?
  • @JessedeBruijne 相同的结果,这很有趣,因为我可以使用 console.log 获得变量的正确状态,但我无法设置它。
  • @MotiKorets 这应该是 testelement,我的错,刚刚编辑了它。

标签: javascript class variables call aurelia


【解决方案1】:

您可能只是注入了一个不同的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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 2012-06-22
    • 2011-03-24
    • 1970-01-01
    • 2010-12-15
    • 2020-03-14
    相关资源
    最近更新 更多