Is Code-behind a module or not?


#1

As in some examples that i found i’ve been trying to declare a variable at the top level of a code-behind file:


import { EventData, Observable, PropertyChangeData } from "tns-core-modules/data/observable";
import { topmost } from "ui/frame";
import { NavigatedData, Page } from "ui/page";
import { ReportsViewModel } from "./reports-view-model";

let page: Page;
let pageData: ReportsViewModel;

export function onNavigatingTo(args: NavigatedData) {
    if (args.isBackNavigation) {
        return;
    }
    page = <Page>args.object;
    pageData = new ReportsViewModel();
    page.bindingContext = pageData;
}

export function onPageLoaded(args: NavigatedData) {
    const height = page.height;
}

But the ‘page’ variable is coming back undefined in the onPageLoaded() handler function.
The export syntax points to code-behind being a module. In that case module level variables should be available to all module’s functions.

Can anybody shed some light on this problem.
This project is pure NativeScript with TypeScript. No Angular involved.

Thanks.


#2

Your page will be loaded before navigatedTo there fore it’s undefined. Since it’s page load you can directly access the page using args.object.


#3

When i move the page variable assignment to the onLoaded handler the page variable is still undefined in the onNavigatedTo, which happens after onLoaded


#4

The reason i’d like to have a module level variable is to avoid repeating the same lines to get page and page binding context in every function.


#5

It works as expected when I set the page variable in loaded event, its accessible in the navigatedTo event.

Please try to create a playground example where we can reproduce the issue if the problem still persists on your end.


#6

thanks for the confirmation. looking at it again.


#7

I setup the app on playground and it worked there. so i went back to my code and figured out that
the VSC debugger will report the module scope variable as undefined inside a function unless the variable is actually used in that function. If it’s not mentioned in the body of the function the variable is not set.
I must presume that this behavior has to do with some kind of optimization but it’s definitely not intuitive and i haven’t seen any mention of that anywhere.

Thanks for taking a look and helping out.


#8

Try to not update the title with resolved but mark the right solution which will be more appropriate and helpful for others.


#9

done. thanks for pointing it out.