Event Listener to initialize variables?


#1

Hi there!

I’m a programmer that has always worked with secuential programming, and promises drive me crazy.

Can I initialize or update a global variable with an Event Listener? Or their scope only works within their brackets? { }
eg:

document.addEventListener("online", function() {
   $scope.hasInternet = true;
}, false);

This works, I can detect the app has Internet, or when not.

But I want to access to this variable in other controllers. For example, before to launch a function, at the time of press a button.

hasInternet == true? good, do 1st ! Has Not? ohh, then do 2nd.

So maybe this is not the best way to have global variables updated, what do you think??

Trying to catch up on chaining promises… . I neeed patience. Thank you!


#2

Hello,

you should use GLOBAL VARIABLE, define it in app.js in top of file.

ex: IS_ONLINE = FALSE;

then you code in app.run function. and set it to true.

IS_ONLINE = false;
.......
.run(function(){
// your code
}


#3

i recommend to use a factory or local storage to store your status
like
when your network status changed just update the value using factory or localstorage because its very easy to for the inter controller communication
you can check the status of this stored variable from any other controller


#4

I have this var in a .service

.service('InternetService', function(){
    var hasInternet = undefined;
})

The thing is that to chekc if the app has connection, I have to wrap the Online or Offline function in a addEventListener.

so when I call this outter var:

.run(){
   document.addEventListener("online", function() {
       InternetService.hasInternet = true;
   }, false);
}

Controller:

if(MyService.hasInternet == true){ 
  console.log("Great! You have Internet!");
}else{
   console.log("Erm wait you don't! Sorry!");
}

Always ELSE works.

The status of MyService.hasInternet == undefined at the time of the IF comparison. Seems that it checks first the IF sentence, and later finishes initializing the variable, wherever it is.

Promises are driving me nuts. =( They always work at the end, when I write them at the top.


#5

i think the problem is the variable not setting
just try like this

.service('InternetService', function(){
var hasInternet = undefined;

this.updateStatus=function(status){
 hasInternet=status;
}
this.getStatus=function(){
 return hasInternet;
}
} )

in your controller update variable using the function

 .run(){
 document.addEventListener("online", function() {
   InternetService.updateStatus(true);
 }, false);
}



internetStaus=InternetService.getStatus();
 if(internetStaus== true){ 
 console.log("Great! You have Internet!");
}else{
  console.log("Erm wait you don't! Sorry!");
}

hope this will work