Aurelia打字稿和DI

时间:2015-09-25 23:20:07

标签: typescript aurelia aurelia-binding

我遇到了一个问题,我希望该对象(示例中的申请人)引用相同,但在此示例中没有得到预期的行为,如果有人能指出我正确的方向,那就太好了。

app.ts:

@inject(HttpClient, Applicant)
export class App {
    applicant: Applicant;
    http: HttpClient;
    router: Router;

    constructor(httpClient, applicant) {
        this.applicant = applicant;
        this.http = httpClient;
        this.applicant.firstName = "John";
    }
//router config code..
updateApplicant() {
    this.http.get("/fakeApplicant.json")
        .then(response => {
            this.applicant = response.content; //Sets first name to Mike
        });
}

start.ts

@inject(Applicant)
export class start {
    router: Router;
    applicant: Applicant;

    constructor(applicant : Applicant) {
        this.applicant = applicant;
    }

app.html

<template>
<div class="container">
    <div class="appHost">
        <router-view></router-view>
    </div>

    <button click.delegate="updateApplicant()">Update First Name</button>

    <h3>App First Name: ${applicant.firstName}</h3>
</div>

的start.html

<template>
<h1>Start</h1>

<h3>Start First Name: ${applicant.firstName}</h3>
</template>

好的,所以上面应该很简单,我有主应用程序,start.html只是一个路由,将在路由器视图中启动时加载。正如所料,App和Start First Name绑定最初都显示为John。但是,当我单击执行http get调用的updateApplicant委托时,只有应用程序名称绑定更新为Mike,我也希望更新Start视图的申请人,因为他们应该引用相同的申请人对象,对吗?我对Aurelia来说相当新,不确定我在DI中注入申请人在不同视图中使用的方式是正确的方式,我期待申请人的对象是单身人士,想要在应用程序中注入不同的视图。我最初认为这是一个词汇范围界定问题,但这意味着什么都不应该更新。

1 个答案:

答案 0 :(得分:2)

行为

不,你不是。由于JS变量只是对内存中对象的引用,因此变量applicant只是一个引用,当您在函数updateApplican中更改它时,您只需更改对另一个对象的引用记忆。这意味着start视图中的引用仍然引用旧引用。

解决方案

有一招。您可以将Aplicant存储在包装器中。它看起来像下面

 //make it also singleton
 class AplicantWrapper {
       aplicant: Aplicant;
 }

然后将其注入您的观点

@inject(HttpClient, ApplicantWrapper)
export class App {
applicantWraper: ApplicantWrapper;
http: HttpClient;
router: Router;

constructor(httpClient, applicant) {
    this.applicantWraper = applicant;
    this.http = httpClient;
    this.applicant.firstName = "John";
}
   //router config code..
 updateApplicant() {
      this.http.get("/fakeApplicant.json")
          .then(response => {
                this.applicantWrapper.applicant = response.content; //Sets first name to Mike
          });
  }

在这种情况下,两个视图都会发生更改,因为它仍然引用相同的包装器对象