Skip to content Skip to sidebar Skip to footer

Javascript Prototype Access This

I have a javascript 'class' which contains a wrapper method to call jquery .ajax(). I want to pass in the onSuccess and onError function handlers, but am not sure how. I can do thi

Solution 1:

The problem is that when the success callback is called by the $.ajax function, the default context is used window. You need to tell JQuery that you want a different context, so you can do one of 3 things:

Add a context attribute to the hash that is sent to $.ajax, so I your case you can do:

$.ajax({
   url: url,
   context: this, // this will tell JQuery to use the right context
   success: this.onSuccessHandler
});

Use JQuery's $.proxy function, like:

$.ajax({
    url: url,
    success: $.proxy(this.onSuccessHandler, this) // this will bind the correct context to the callback function
});

Cache the variable this, like @mVChr suggested, although I would encourage you to use self as it has become somewhat of a javascript idiom

var self = this;
 $.ajax({
     url: url,
     success: function(data) {
         self.onSuccessHandler(data);
     }
 });

Edit:

If you need a more in depth explanation of context and scope in javascript checkout this article: http://www.digital-web.com/articles/scope_in_javascript/

Solution 2:

Cache this within the local scope of _makeAjaxCall before conducting the ajax call:

X.prototype._makeAjaxCall = function(url, onSuccessHandler, onError){
  var _X = this; // cache this

  $.ajax({
    url : url,    
    success : function (jsonData, textStatus, XMLHttpRequest) {
      // use cached this
      _X.onSuccessHandler();
    }
  });
}

Solution 3:

Thanks to input from CarlosZ & mVChr, I've figured out the solution, http://jsfiddle.net/bX35E/3/

$(document).ready(functiontestApp() {
  newX();
});

functionX() {
  console.dir(this);
  var initUrl = "/echo/json/";
  this._instanceVariable = "I AM defined!";
  // Init X by making Ajax call, passing the func to be called on ajax returnthis._makeAjaxCall(initUrl, this.onSuccessInit(), this.onError);
  // Make another ajax call to init another componentthis._makeAjaxCall(initUrl, this.onSuccessSomeOtherAjaxCall(), this.onError);
}

X.prototype.onSuccessInit = function(){
  //this.doStuff(...);var self = this;
    returnfunction() {
       alert("onSuccessInit, _instanceVariable="+self._instanceVariable);
    }
}

X.prototype.onSuccessSomeOtherAjaxCall = function(){
    var self = this;
    returnfunction() {
      alert("onSuccessSomeOtherAjaxCall, _instanceVariable="+self._instanceVariable);
    }    
}

Post a Comment for "Javascript Prototype Access This"