2016-07-14 85 views
0

我的理解是,通過view-model.ref,我可以從組件外部訪問組件的視圖模型,稱之爲功能。從Aurelia w/TypeScript組件外部調用組件視圖模型函數時,「Can not read property of undefined」

下面的代碼將導致無法讀取屬性 'LoadForAdditionalLocations' 未定義

成分的導入

export class UserLocationSelector { 
    public LoadForAdditionalLocations(reportLogin:string, addLocationsLogin:string){ 
     ///do stuff 
    } 
} 

頁面組件上(TS文件)

export class AddLocation{ 
    attached(){ 
     this.UserLocationSelector.LoadForAdditionalLocations("user1","user2"); 
    } 
} 

該組件處於打開狀態的頁面(htmlf ILE)

<template> 
    <require from='user-location-selector'></require> 
    <div> 
     <user-location-selector view-model.ref="UserLocationSelector"></user-location-selector> 
    </div> 
</template> 

回答

3

傳遞給裁判屬性的名稱將成爲您的虛擬機的屬性,所以它必須使用this.進行訪問。出於這個原因,建議您遵循JavaScript命名約定。

元器件導入

export class UserLocationSelector { 
    public loadForAdditionalLocations(reportLogin:string, addLocationsLogin:string){ 
     ///do stuff 
    } 
} 

頁該組件是在(TS文件)

export class AddLocation{ 
    userLocationSelector; 

    attached(){ 
     this.userLocationSelector.loadForAdditionalLocations("user1","user2"); 
    } 
} 

頁該組件是在(HTMLFILE)

<template> 
    <require from='user-location-selector'></require> 
    <div> 
     <user-location-selector view-model.ref="userLocationSelector"></user-location-selector> 
    </div> 
</template> 

下面是一個例子的要點:https://gist.run/?id=96774bc2d99de0b421880b8977f081d4

+0

我實際上是使用this.UserLocationSelector並導致相同的錯誤。 –

+0

我已經添加了一個示例gist –

+0

我可以使用javascript來使用它。不過在TypeScript中。 –

相關問題