Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nativescript - how set global variables

Tags:

nativescript

I'm starting with nativescript with latest version.

I've finished tutorial on offical page, but now i have more questions than answers.

Can anybody tell me, what strategies can i use to set some variables, for example after succesfull login, how to set variable or even better, run some function that is doing checks globally, and not on every view or model file ? I see that app.js is starting point for app, but looks like it cannot do any global checks ?

I think, second question is related : Almost every model view file (file called as {viewname}).js is using:

var frameModule = require('ui/frame');

Is there a way to declare this once ? Or i have to run this every time when i need frame methods ? Or maybe if this is possible, lead to poor perforance?

Thanks for any advices.

like image 497
Marek Brzeziński Avatar asked May 03 '26 23:05

Marek Brzeziński


2 Answers

NativeScript has a global Variable Scope.

To use it add global. in front of a variable name:

global.userName = "usernameXYZ";

To call it:

console.log("Username= "+global.userName);
like image 195
null Avatar answered May 05 '26 13:05

null


Thanks Nikolay. Im using this pattern (maybe will help somebody) register JS:

var page = require ("ui/core/view");
var frameModule = require('ui/frame');
var appSettings = require('application-settings');

exports.loaded = function(args) {
page = args.object;
};

exports.register = function() {
var userName = page.getViewById('userName');
var userPass = page.getViewById('userPass');

if (userName.text != '' &&  userPass.text != '') {
    var name = userName.text;
    var pass = userPass.text;

    appSettings.setString('name', name);
    appSettings.setString('pass', pass);
    appSettings.setBoolean('auth', true);

    var topmost = frameModule.topmost();
    var navigationEntry = {
        moduleName: "main-page",
        context: { info: "something you want to pass to your page" },
        animated: true,
        transition: "curlDown",
        clearHistory: true
    };
    topmost.navigate(navigationEntry);

} else {
    alert('Please, fill form');
}
};
like image 33
Marek Brzeziński Avatar answered May 05 '26 12:05

Marek Brzeziński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!