0

This is my code:

class MenuManager{
  constructor(menuSource){
    this._src = menuSource;
    this._menudata;
  }
  get src(){
    return  this._src;
  }
  get MenuData(){
    return this._menudata;
  }
  set menudata(newdata){
    this._menudata = newdata;
    console.dir("MenuData set to: "+ JSON.stringify(this._menudata));
  }
  create(){
    console.log("creating Menu");
    console.log("requesting Menu from source:"+ this._src);
    try{
      if(document.getElementById("menu-placeholder") == null){
        throw "MenuManager: Menu Placeholder not found. Please create an <div>-Element with id 'menu-placeholder' and an unique data-menu-id attribute to contain a menu. If the <div>-Element is created, then check if #<MenuManager>.create() is executed after DOMContent is loaded.";
      }
    }
    catch(error){
      throw new Error(error);
    }
    let tempdata = "tempdata variable";
    let req = new XMLHttpRequest();
      req.onload = (event) => {
        tempdata = "new data";
        console.log("MenuManager / "+this._src);
        console.log("inside function : "+tempdata);
      }
      req.open(
        'GET',
        this._src
      );
      req.setRequestHeader("Accept","text/json");
      req.send();
      console.log(tempdata);
  }
}

My problem seems to be so easy! I just want to initalize the tempdata - variable to be "new data" . I already read about the hoisting-phenomenon, but somehow i didn't get it to work. I can't understand why i am not able to easily initialize the global variable tempdata. Much thanks for any help!

laim2003
  • 299
  • 4
  • 19
  • you are logging is before request got response. your variable has got the value you mentioned. Just moce the consolelog(tempdate) statement inside `.onload` – Muhammad Usman May 20 '18 at 18:35
  • @George Bailey oh yes thanks. i totally forgot about the asynchrounus-thing. – laim2003 May 20 '18 at 18:45

0 Answers0