Jonathan Lebrun
Jonathan Lebrun

Reputation: 1552

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

I have this :

var MyObject = function(){   
   this.url = "monurl";   
   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 ?

Upvotes: 0

Views: 530

Answers (5)

frglps
frglps

Reputation: 721

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);
} }

Upvotes: 1

Tivac
Tivac

Reputation: 2573

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);
    }
}

Upvotes: 0

Max Shawabkeh
Max Shawabkeh

Reputation: 38603

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);
  }
}

Upvotes: 0

Jonathan Lebrun
Jonathan Lebrun

Reputation: 1552

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.

Upvotes: 0

miensol
miensol

Reputation: 41608

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);
};

Upvotes: 0

Related Questions