Samuel Elrod
Samuel Elrod

Reputation: 337

"Cannot read property of undefined" when calling a components view model function from outside the component in Aurelia w/ TypeScript

It was my understanding that with view-model.ref I could access the viewmodel of the component from outside the component and call it's functions.

Below code results in Cannot read property 'LoadForAdditionalLocations' of undefined

Component to Import

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

Page that component is on (TS file)

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

Page that component is on (htmlfile)

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

Upvotes: 1

Views: 687

Answers (1)

Ashley Grant
Ashley Grant

Reputation: 10887

The name you pass to the ref attribute becomes a property on your VM, so it must be accessed using this.. For this reason, it's recommended you follow JavaScript naming conventions.

Component to Import

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

Page that component is on (TS file)

export class AddLocation{
    userLocationSelector;

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

Page that component is on (htmlfile)

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

Here's an example gist: https://gist.run/?id=96774bc2d99de0b421880b8977f081d4

Upvotes: 3

Related Questions