"this" value inside callbacks


#1

I have a view with the “code behind” typescript code. The module exposes an instance of a class, but the callbacks fire without “this” set to the instance. Can someone explain how this is supposed to work. I know I can pull the control from args: EventData and get to the page, and use its bindingContext, but why doesn’t “this” simply work?

<Page class="page" loaded="onLoaded">
  <StackLayout>
     <Label tap="welcomeTap" text="Hello!"/>
   </StackLayout>
</Page>

and

import { EventData } from "data/observable";

class WelcomePage {
    constructor(public name: string) {};

    onLoaded(args: EventData) {
        console.log(this.name); // => Undefined
    }
    welcomeTap(args: EventData) {
        console.log(this.name); // Fails due to this being undefined
    }
};
export = new WelcomePage('Mike');

#2

Lots to wrap my head around with how exports work. Here’s something that works and has the proper context I was looking for. Is there a better way?

<Page class="page" loaded="onLoaded" navigatedTo="{{ navigatedTo }}">
  <StackLayout>
     <Label tap="{{ welcomeTap }}" text="{{ name }}"/> 
     <!--Shows "Mike"-->
   </StackLayout>
</Page>

and

import { EventData } from "data/observable";
import { Page } from "ui/page";

class WelcomePage {
    constructor(public name: string) {};

    onLoaded(args: EventData) {
        console.log(this.name); // => "Mike"
    }
    welcomeTap(args: EventData) {
        console.log(this.name); // => "Mike"
    }
    navigatedTo(args) {
        console.log('navigatedTo') // called
    }
};

export function onLoaded(args: EventData) {
    var page = <Page>args.object;
    page.bindingContext = new WelcomePage('Mike');
    page.bindingContext.onLoaded(args);
}

#3

Don’t know what’s wrong exactly, but I think your class WelcomePage should extend Observable:

class WelcomePage extends Observable {
    ...

Don’t know if it’ll help


#4

Nope. Still fails the first example.

import { EventData, Observable } from "data/observable";

class WelcomePage extends Observable {
    public name;
    constructor() {
        super();
        this.name = "Steven";
    };

    onLoaded(args: EventData) {
        console.log(this.name); // => Undefined
    }
    welcomeTap(args: EventData) {
        console.log(this.name); // Fails due to this being undefined
    }
};
export = new WelcomePage();

#5

I’ll try tomorrow.
I just started a new job today, so I’m slightly preoccupied, haha.

:slight_smile: