Kinorsi
Kinorsi

Reputation: 553

How to retrieve class member in dojo/request promise

I use dojo/reqeust and delcare to make a test.

I declare a new class with a function which will use dojo/request to make a query. In the promise function, I can't retrieve the this member.

   var TestJson = declare(null, {
       name: "hello",
       doJson: function(){
          request.post("someTarget").then(function(res){
             alert(this.name);
          });
       }
  });

   var obj= new TestJson();
   obj.doJson();

As above, when post returned, the alert(this.name) invoked. But this points to the Window object, so this.name is undefined, not pointed to TestJson.name. So how can I retrieve TestJson.name? Thanks!

Upvotes: 1

Views: 249

Answers (1)

McDowell
McDowell

Reputation: 108939

There are a couple of ways you can solve this problem.

Refer to a variable in the closure scope:

var TestJson = declare(null, {
  name: "hello",
  doJson: function(){
    var instance = this;
    request.post("someTarget").then(function(res){
      alert(instance.name);
    });
  }
});

Use the dojo/_base/lang module to set the execution context on the callback:

var TestJson = declare(null, {
  name: "hello",
  doJson: function(){
    var callback = lang.hitch(this, function(res){
      alert(this.name);
    });
    request.post("someTarget").then(callback);
  }
});

Upvotes: 2

Related Questions