dqhendricks
dqhendricks

Reputation: 19251

Solution for using `this` keyword in ajax calls within methods?

I am creating a JavaScript class. Some of the methods contain AJAX calls using JQuery. The problem I am comming accross is that I cannot use the this keyword within the AJAX callbacks due to a change in scope. I have come up with a hackey solution, but I am wondering what is the best practice way around this?

Here is an example:

var someClass = function() {

   var someElement = $('form');

   this.close = function() {
      someElement.remove();
   };

   this.query = function() {
      $.ajax({
         url: someurl,
         success: function() {
            this.close(); // does not work because `this` is no longer the parent class
         }
      });
   };
};

Upvotes: 3

Views: 1207

Answers (3)

puk
puk

Reputation: 16752

I prefer to use anonymous functions because you get local variables, and you don't have to create variables using var which I find clumsy in the middle of a block of code.

var someClass = function() {

   var someElement = $('form');

   this.close = function() {
      someElement.remove();
   };

   this.query = function() {
      (function(self, someurl){
          $.ajax({
              url: someurl,
              success: function() {
                 self.close();
              }
          });
      }(this, someurl));
   };
};

In this example it is not necessary to include someurl as a parameter, however, it comes in handy when you want to make local copies of global variables which could change value while waiting for a response.

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Simply use the context parameter to pass any object you wish to the success callback:

$.ajax({
    url: someurl,
    context: this,
    success: function() {
        this.close(); // this is what it was when we triggered the AJAX call
    }
});

You could also pass complex objects and stuff:

$.ajax({
    url: someurl,
    context: { foo: 'bar', element: this },
    success: function() {
        alert(this.foo);
        this.element.close();
    }
});

Upvotes: 13

John Strickler
John Strickler

Reputation: 25421

Store a reference to this - my convention has been to use self.

var someClass = function() {

   var self = this, //<--- store a reference
       someElement = $('form');

   this.close = function() {
      someElement.remove();
   };

   this.query = function() {
      $.ajax({
         url: someurl,
         success: function() {
            self.close(); // does not work because `this` is no longer the parent class
         }
      });
   };
};

Upvotes: 2

Related Questions