0

I have a simple .html page like this :

</html>
<head>

<script type="text/javascript" src="jquery/jquery-1.8.2.js"></script>
...
<script type="text/javascript">

var obj;             

function document_load() {
      obj = new mySpace.myClass(); 
      console.log("end document load");          
   }


</script>
</head>
<body onload="document_load()">
...
...
</body>
</html>

myClass is a TypeScript class with this constructor :

 public constructor() {

    console.log("begin constructor");

    (<any>$).when(

      jQuery.getJSON('path/myJson1.json', function (data) {
       this.obj1 = data;
       console.log("here1");
        }),

       jQuery.getJSON('path/myJson2.json', function (data) {
       this.obj2 = data;
       console.log("here2");
        })

       ).then(function () {

          if (this.obj1 && this.obj2) {

           console.log("here3");
           this.obj3 = new myClass3();
           this.obj4 = new myClass4(); 
           console.log("everything went ok");

        }
     });
   } 

Actually the console prints this :

begin constructor
end document load
here1
here2

The reason of this behaviour is (of course) cause of asynchronous jQuery calls (or at least I guess). How can I obtain the following behaviour?

begin constructor
here1
here2
here3
everything went ok
end document load

I clarify that the jsons are taken correctly (I tried to print them and they are correct).

Fabrizio Morello
  • 335
  • 1
  • 5
  • 18
  • I'd suggest to have a look at [Is it bad practice to have a constructor function return a Promise?](http://stackoverflow.com/q/24398699/1048572) – Bergi Mar 17 '15 at 16:47

2 Answers2

0

That's because you're not returning a promise to jQuery.when, so the callback gets called and this.obj1 && this.obj2 are both null.

A better way to do this would be:

(<any>$).when(

    jQuery.getJSON('path/myJson1.json'),

    jQuery.getJSON('path/myJson2.json')

)
.then(function (obj1, obj2) {
    // Code
});
Rodrigo Siqueira
  • 1,164
  • 8
  • 20
  • He *does* pass promises to `$.when`, but that doesn't fix the `this` context of his callbacks. – Bergi Mar 17 '15 at 16:48
0

Replace all functions with arrow functions (=>). This will ensure that "this" points to the correct thing in all function bodies.

More : https://www.youtube.com/watch?v=tvocUcbCupA

basarat
  • 261,912
  • 58
  • 460
  • 511
  • I think the problem is not only the "this" statement. In fact, if I try to remove the "if" clause, the console print [ begin constructor,end document load,here1,here2,here3,everything went ok ] – Fabrizio Morello Mar 18 '15 at 09:09