开发者

How to acces a global variable in a callback object in javascript YUI without use window.myvariable?

开发者 https://www.devze.com 2022-12-28 15:37 出处:网络
I have this : var MyObject = function(){ this.url = \"monurl\";开发者_如何学Go this.mavar = \"\";

I have this :

var MyObject = function(){   
   this.url = "monurl";   开发者_如何学Go
   this.mavar = "";   
   this.Load = function(){
     var callback = {
       success: function(o){
         mavar = o.responseXML.getElementsByTagName("montag")[0].firstChild.nodeValue;
       }
     }
     YAHOO.util.Connect.asyncRequest('GET',url,callback);
} }

the mavar variable is not accessible. How can I do this ?


I believe you can set a scope param to the callback. So you should be able to do something like the following.

var MyObject = function(){   
   this.url = "monurl";   
   this.mavar = "";   
   this.Load = function(){
     var callback = {
       success: function(o){
         this.mavar = o.responseXML.getElementsByTagName("montag")[0].firstChild.nodeValue;
       },
       scope: this
     }
     YAHOO.util.Connect.asyncRequest('GET', this.url, callback);
} }


You could also do it like this:

var MyObject = new function(){   
   this.url = "monurl";   
   this.mavar = "";   
   this.Load = 
   (function(that){ 
        return function(){
            var callback = {
                success: function(o){
                    that.mavar = o.responseXML.getElementsByTagName("montag")[0].firstChild.nodeValue;
                }
            }
            YAHOO.util.Connect.asyncRequest('GET',url,callback);
        } 
    })(this);
};


In my object, I add a variable that's reference the this :

var selfMyObject = this;

and I replace the this.mavar to selfMyObject.mavar in success callback and it's work fine.


Save the this variable:

var MyObject = function() {   
   this.url = "monurl";   
   this.mavar = "";   
   this.Load = function() {
     var me = this;
     var callback = {
       success: function(o) {
         me.mavar = o.responseXML.getElementsByTagName("montag")[0].firstChild.nodeValue;
       }
     }
     YAHOO.util.Connect.asyncRequest('GET',url,callback);
  }
}


The best way to handle this is to let YUI do your scope correction, since support is built in. Here's the docs page telling you how to to do it. http://developer.yahoo.com/yui/connection/#scope

var MyObject = function() {
    this.url = "monurl";
    this.mavar = "";
    this.Load = function() {
        var callback = {
            success: function(o){
                this.mavar = o.responseXML.getElementsByTagName("montag")[0].firstChild.nodeValue;
            },
            scope: this
        }

        YAHOO.util.Connect.asyncRequest('GET', url, callback);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消