Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 7th, 2012  |  syntax: None  |  size: 1.08 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to solve this JavaScript scope issue
  2. var news;
  3. $.get('news.txt', function (dat) {
  4.    news = dat;
  5.    if ($('#removeN').is(':checked')) {
  6.        news = "";
  7.    }
  8.    alert(news) // Displaying exact result;              
  9. });
  10. alert(news) // Displaying undefined..; Why?
  11.        
  12. var news;
  13. $.get('news.txt', function (dat) {
  14.    news = dat;
  15.    if ($('#removeN').is(':checked')) {
  16.        news = "";
  17.    }
  18.    alert(news) // BEFORE THIS!        
  19. });
  20. alert(news) // THIS EXECUTES
  21.        
  22. $.get('news.txt', function (dat) {
  23.    news = dat;
  24.    if ($('#removeN').is(':checked')) {
  25.        news = "";
  26.    }
  27.    doSomething(news) // Displaying exact result;              
  28. });
  29.  
  30. var doSomething = function(data) {
  31.     alert(data);
  32. }
  33.        
  34. var news;
  35. $.get('news.txt', function (dat) {
  36.    //process news      
  37. }).done(function(dat){
  38.    //display news, or maybe more processing related to this particular function block
  39.    alert(news);
  40. }).fail(function(){
  41.    //oops, something happened in attempting to get the news.
  42.    alert("failed to get the news");
  43. }).always(function(){
  44.    //this eventually gets called regardless of outcome
  45. });