简体   繁体   中英

Calling JavaScript method in a particular scope

Dear All, I'm using dojo.declare to create classes in JavaScript. In one of the methods, I've an AJAX request. In the load method of that request, I need to execute certain methods.These methods are actually methods of the class that was created using dojo.declare. I tried to execute the method using this . But it gave me method not found error. So I used dojo.hitch(this,testMethod) to invoke it. It worked fine. Now the problem is I've lot of other methods also inside testMethod() which internally calls other methods of my JavaScript class. It is really a pain to have dojo.hitch() everywhere. Is there any work around for this.

    dojo.declare("TestClass",null,{

    getData:function(url){
    dojo.xhrGet({
      url:url,
      load: function (response){
        dojo.hitch(scope of the current object,testMethod(response))    
      },
      error:function(){

      }
    });
    },
    testMethod:function(response){
    //calls testMethod2. I think I can use dojo.hitch(this,testMethod3) to call it.
    //but I wanted to avoid doing it every time.
    },
    testMethod2:function(){
    //calls testMethod3
    },
    testMethod3:function(){
    //can call other methods.
    }
    });

It seems like that execution scope was lost in this code:

load: function (response){
        dojo.hitch(this,testMethod(response))   
      },

I made small changes in your code. Now it should work properly.

dojo.declare("TestClass",null,{

        getData:function(url){
        dojo.xhrGet({
          url:url,
          load: dojo.hitch(this,this.testMethod),
          error:function(){

          }
        });
        },
        testMethod:function(response){
           this.testMethod2();
        },
        testMethod2:function(){
           this.testMethod3();
        },
        testMethod3:function(){
        //can call other methods.
        }
        });

This is a typical context problem. You are passing an uncontexted function as a property of a configuration hash, which is passed as argument to dojo.xhrGet.

dojo.hitch is exactly the right construct to add a context to a function. Another way is to simply use a closure. Is there any reason why you can't do:

var me = this;
dojo.xhrGet({
    url:url,
    load: function(response) {
        me.testMethod(response);
    }
});

Try doing it like this:

dojo.xhrGet({
   url:url,
   load: dojo.hitch(this, "testMethod"),
   error:function(){

   }
});

Your way worked as well, but it saves you a few bytes and is just cleaner to use the method name as a string. Hitch will automatically pass the arguments for you.

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