Code-behind from one page works on other pages too



I wanted to create the ‘double back to exit’, that is, on my first screen (welcome screen), if a user presses back button, he gets a toast “Press back again to exit”. Then when he presses the button again, he’ll exit out of the app. I used some code from here

The code works but if I go to login or signup screen and press back button, I still get the toast and iif I press the back button again, then I come back to the welcome screen. I don’t get it, this code is placed in so it should only be working on this page, not all of them. Right? Am I missing something

var application = require("application");
var Toast = require("nativescript-toast");
const WelcomeViewModel = require("./Welcome-view-model");
const appSettings = require("application-settings");
const frameModule = require("ui/frame");

let nextCancel = true;
let nextCancelResetterHandle;

if ( {, function(args) {
	if (nextCancel) {
		args.cancel = true;
      // toast is a community plugin, see:
      Toast.makeText('Press back again to exit.').show();

      if (nextCancelResetterHandle) {

      // enable exit if back button is tapped within 1 sec
      nextCancel = false;
      nextCancelResetterHandle = setTimeout(function() {
      	nextCancel = true;
      }, 1000);

/* ***********************************************************
* Use the "onNavigatingTo" handler to initialize the page binding context.
function onNavigatingTo(args) {
	const page = args.object;
	page.bindingContext = new WelcomeViewModel();

	const checkLogin = appSettings.getString("sessionId");
	if(checkLogin != undefined){
		console.log('not logged in');

exports.onNavigatingTo = onNavigatingTo;

exports.login = function(){
	var topMost = frameModule.topmost();

exports.signup = function(){
	var topMost = frameModule.topmost();

And my login screen does not have any of this code.

Here’s the welcome screen for easy understanding of the concept.



A back-button event is triggered on Activity, Page !== Activity - A page is something equal to fragment in Android.

Here I have a workaround to fire back-button event on Page level.


Hi. Sorry to bother you but could you explain how this work or is there a vanilla js version because I don’t know typescript.


There is nothing specific to TypeScript if you just remove the typings, you may use a TypeScript compiler to get JS version of code.