I have two huge issues with this
scope in my javascript code.
After creating setAJAXGet
object, callback function was lost and couldn't be called correctly. So instead of calling this.funct
I set ajax.parent = this
; and call this.parent.funct
- works ok.
function setAJAXGet() {
this.askServer = function() {
var ajax = new XMLHttpRequest();
ajax.parent = this;
ajax.contentType = "charset:utf-8";
ajax.onreadystatechange = function() {
if (ajax.readyState==4 && ajax.status==200) {
this.parent.funct(ajax.responseText);
}
}
ajax.open( "GET", this.url+'?'+this.vars, true );
ajax.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
if (navigator.onLine) ajax.send( null ); else this.functError();
}
this.functError;
this.funct;
this.vars;
this.url;
}
Things get a little more complicated when I try to call setAJAXGet()
from the other object and the callback function is inside that object. Callback function is called correctly, but every other function in the object (from the callback function) gets invisible.
function someObject() {
this.asyncGet = function() {
var get = new setAJAXGet();
//do some config here...
get.funct = this.processAsyncData;
get.askServer();
}
this.someOtherFunction = function() {
}
this.processAsyncData = function(ajaxText) {
// ajaxText is OK
this.someOtherFunction();
// this.someOtherFunction is not defined (how so?)
}
this.asyncGet();
}
I can solve this problem by passing object to the processAsyncData
by modified setAJAXGet()
as argument, but it looks ugly.
function someObject() {
this.asyncGet = function() {
var get = new modifiedSetAJAXGet();
//do config here...
get.object = this; // stores 'this' and sends it to callback as argument
get.funct = this.processAsyncData;
get.askServer();
}
this.someOtherFunction = function() {
}
this.processAsyncData = function(object, ajaxText) {
// ajaxText is OK
object.someOtherFunction();
// object.someOtherFunction works just fine
}
this.asyncGet();
}
I believe that you know more elegant solution.