views:

54

answers:

2

In using a jquery callback, I found that 'this' isn't defined anymore. I've found a work around, which is to set 'this' to another variable. For example, like so:

function handler(DATA) {
       var myThis = this;

       $.post(
          'file.php',
          DATA,
          function() {

               // THIS where I need access to 'this', but its not available
               // unless I've used the 'myThis' trick above

          }
       );
}

It works like this, but I am always looking for 'the right way' or 'the better way' to do things.

Is this the best way? or is there another?

+5  A: 

This is fine. I do this all the time in my projects, especially with Ajax calls.

But, make sure to put var before myThis, or else it will be declared in global scope, which you most definitely don't want.

function handler(DATA) {
       var myThis = this;

       $.post(
          'file.php',
          DATA,
          function() {

               // THIS where I need access to 'this', but its not available
               // unless I've used the 'myThis' trick above

          }
       );
}
Jacob Relkin
Yeah, I actually had var in my code, but I didn't copy/paste for whatever reason :) I was hoping there was a smoother, slicker way but there isn't always.
Stomped
+1  A: 

I like using "self":

function handler(DATA) {
   var self = this;
   $.ajax({
      "url":"file.php",
      "type":"post",
      "data":DATA,
      "success":function() {
           // THIS where I need access to 'this', but its not available
           // unless I've used the 'myThis' trick above
      },
      "error":function(){
          alert("ERROR!")
      }
    });
}

you can also use jQuery's proxy method...but it would probably be overkill for this situation.

function handler(DATA) {
   var success = $.proxy(function(){
       // use "this" in this function to refer to the scope 
       // you were assigning to "myThis" in your example
   }, this);
   $.ajax({
      "url":"file.php",
      "type":"post",
      "data":DATA,
      "success":success,
      "error":function(){}
  });
}
David Murdoch