-2
export class PizzaController{

    static loadData(){
        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            dynamicSelect(xhttp.responseXML);
          }
        };     
        xhttp.open("GET", "js/data/pizzadata.xml", true);
        xhttp.send();
    }

    dynamicSelect(xmlDoc){
        var doughTypes = [];

        let selects = document.getElementById("selects");

        let doughSelect = document.createElement("select");
        doughSelect.setAttribute("id","dough");
        selects.appendChild(doughSelect);

        let typeSelect = document.createElement("select");
        typeSelect.setAttribute("id","type");
        selects.appendChild(typeSelect);

        let toppingSelect = document.createElement("select");
        toppingSelect.setAttribute("id","topping");
        selects.appendChild(toppingSelect);    


        let x = xmlDoc.getElementsByTagName('DOUGH');
    }
}

Im trying to extract data from XML file and create a dynamic selector on webapp. The code works when it is procedural i.e. not "OOP" but, I have to do it this way. PizzaController class is being called by init.js and im calling just loadData. When I tried to console log it showed results so the calling works thus this must be the only problem. I keep getting this error

Uncaught ReferenceError: dynamicSelect is not defined
    at XMLHttpRequest.xhttp.onreadystatechange 

1 Answers1

0

dynamicSelect is a property of the PizzaController instance, not a variable in the current scope.

Use an arrow function to capture the current instance of PizzaController and then access its properties with this.

    xhttp.onreadystatechange = () => {
      if (this.readyState == 4 && this.status == 200) {
        this.dynamicSelect(xhttp.responseXML);
      }
    };     
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I added your code and this is how i call that function, i got no response on browser window.onload = function () { document.getElementById("add").onclick = PizzaController.loadData; }; – CautionPackage Feb 16 '19 at 09:37
  • @CautionPackage — You've disconnected `loadData` from `PizzaController`, so `this` is lost. See https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Quentin Feb 16 '19 at 09:45
  • document.getElementById("add").onclick = () => PizzaController.loadData() I tried to find the solution but it doesnt say how to call it with classes – CautionPackage Feb 16 '19 at 09:59
  • Looking back at the code … **don't use a class**. You aren't doing anything where it makes sense to use a class. If you really want to use classes, then learn how to use `new` – Quentin Feb 16 '19 at 10:03
  • I have three layer backend so I have to figure something out. Thanks for response anyways – CautionPackage Feb 16 '19 at 10:06