Use global variable in more than one js file

5

I have the file GeraGridDados.js and in this file I created a global variable and a function.

nomeTela = "";

function redirecionaTela() {
    //redireciona para tela que chamou a tela de Dados.
    location.href = nomeTela + ".html";
};

I would like to call this variable ScreenName in another JS GraphicsGrid document and feed it with a value. And when I call the RedirectsType function of GeraGridDados.js on another HTML screen that this value is still fed.

asked by anonymous 08.12.2014 / 14:15

2 answers

10

If you are redirecting you lose the information contained in the variable because the file GeraGridDados.js will load again.

An easy solution to this is to use localStorage

// Armazenar
localStorage.setItem("nomeTela", "Joao");
// Obter
nomeTela = localStorage.getItem("nomeTela");
//Limpar
localStorage.clear();

There are other ways, with sessionStorage, where the data is stored only during the session, ie when closing the browser the data is lost.

Take a look at documentation of LocalStorage.

    
08.12.2014 / 14:22
2

Actually, reading the title of your question, you say how to use global variable in more than one js file , well, responding to this, I can tell you that regardless of how many .js you have included in the page, all the code will be compiled as a all and any variable that is declared this way: variavel = valor will become global in "all .js files", but in your case you is doing a redirect, so all set values will be lost.

So if that's the case, you should use Cookies , or localStorage to store data you want to use in "another screen."

BUT, apparently you do not need to do this , as you probably want the "screen name" that is the name of the .html file you are currently in, which can be redeemed the time that you want only by using location.href :

var addr     = location.href;
var nomeTela = addr.substring(addr.lastIndexOf('/')+1, addr.indexOf('.html'))
alert(nomeTela);
    
08.12.2014 / 14:33