Button Tap from Global Function


#1

How do i have a button tap event call a global function i setup?


#2

Can you share some code?


#3
<Page class="page" 
    xmlns="http://www.nativescript.org/tns.xsd">
    <ActionBar class="action-bar">
        <NavigationButton text="Go Back" android.systemIcon="ic_menu_back" tap="navBack"></NavigationButton>
        <Label class="action-bar-title" text="Settings > Database"></Label>
    </ActionBar>
    <StackLayout>
        <StackLayout>
            <Label text="DATABSE SETTINGS" class="h1 text-center" />
        </StackLayout>
    </StackLayout>
</Page>

app.js

global.navBack = function() {
    console.log("*** Global Nav Back Tap");
    frameModule.topmost().goBack();
};

#4

Normally, I would have a navBack function simply exported, without invoking global scope, as is described here: https://docs.nativescript.org/ui/action-bar#navigation-button


#5

The issue is i dont want to have to declare it on every page. hence the desire to do it globally


#6

Can you include this sort of helper function in one file, and require it as needed: https://docs.nativescript.org/runtimes/require


#7

Yes but again wouldnt be any different than exports i would have to do it on every page. I guess there is no way to achieve this it sounds like


#8

I did find this: https://stackoverflow.com/questions/31502225/adding-a-global-variable-function-in-javascript-specifically-nativescript#31528987


#9

Yeah i saw that and it reference the Variables which i use as well. But cant get the function aspect to work on the binding off the xml to the tap event


#10

Hi,

A bit late, but you can do something like that in a .js file

var applicationResources = application.getResources();

var navBack = function () {
    frameModule.topmost().goBack();
}

applicationResources.navBack = navBack;
application.setResources(applicationResources);

Then require your .js file in app.js (before app start of course) and it should be working