简体   繁体   中英

Calling sibling method after xhr request in custom dojo amd module

I have a custom module for dojo's amd that will be something like this:

define(
  "my/moduleName",
  [//dependencies], 
  function(xhr) {
    return {
      method1: function() {
        xhr.get({
          url: "myurl",
          load: function(data) {
            //handle data
            this.method2(data) //< THIS CAUSES ERROR: 'this.method2 is not a function'
          }
        });
      },

      method2: function(data) {
        //process data
      }
    }
}

I suspect my problem is that xhr.get creates a deferred object, and method2 is not defined in that object but rather on the "my/module" object.

How can I make the method1 call method2 AFTER the xhr has completed?

You need to store the current this context as once you are inside the load function context this is the xhr object.

A common convention is var that = this; then use that inside any other closure as needed.

Store this before the call similar to this:

define(
    "my/moduleName", [ //dependencies], 
function (xhr) {
    return {
        method1: function () {
            var that = this; //<-- store this context

            xhr.get({
                url: "myurl",
                load: function (data) {
                    //handle data
                    that.method2(data); //<-- use that , the stored context
                }
            });
        },

        method2: function (data) {
            //process data
        }
    }
}

DEMO - Store this for later use in another closure


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM