0

I am trying to send JSON data that's been loaded via dojo/request/xhr to a method within my custom class.

when I receive the data inside the .then() function I do not have access to my class instance methods since the data is only contained inside the .then() function call.

require([
  "dojo/_base/declare",
  "dojo/request/xhr"
], function(declare, xhr) {

  declare("rpg.game",null, {

    /**
     * 
     * @param {type} domNode
     * @returns {undefined}
     */
    constructor: function(domNode) {
      domNode.innerHTML = "hello world";
    },

    /**
     * 
     * @param {type} _url
     * @returns {undefined}
     * 
     */
    loadData: function(_url) {

      xhr(_url, {
        handleAs: "json"
      }).then(function(data){
        // Do something with the handled data

        console.log(data); // <-- How can I send this data to my class?
        this.saveData(data); // <-- this does not work

      }, function(err){
        // Handle the error condition

      }, function(evt){
        // Handle a progress event from the request if the
        // browser supports XHR2

      });
    },

    saveData: function(data) {
      this.data = data;
    }
  });
});

I want to send the data to the method saveData but when I call the method, it is "undefined" within the .then() call.

barbsan
  • 3,418
  • 11
  • 21
  • 28

1 Answers1

0

this doesn't reference your class since xhr call is asynchronous, your situation is similar to this issue with Promises.

You can bind proper context using lang.hitch from dojo/_base/lang (this will ensure that also this.data will use correct this):

require([
  "dojo/_base/declare",
  "dojo/_base/lang",
  "dojo/request/xhr"
], function(declare, lang, xhr) {

/*...*/

    loadData: function(_url) {

      xhr(_url, {
        handleAs: "json"
      }).then(lang.hitch(this, function(data){
        // Do something with the handled data

        console.log(data);
        this.saveData(data); // <-- `this` should refer to your class

      }),

Using var self = this; you'll have to set data directly in .then callback (or call saveData with context set to self)

loadData: function(_url) {

  var self = this;
  xhr(_url, {
    handleAs: "json"
  }).then(function(data) {
    // Do something with the handled data

    console.log(data); 
    self.data = data; // set `data` property of your class
//  self.saveData(data); // <-- this does not work because of `this.data` in `saveData`

  }, /**/);
},

saveData: function(data) {
  this.data = data;
}
barbsan
  • 3,418
  • 11
  • 21
  • 28