Search code examples
javascriptjqueryjquery-callback

Getting class instance from jquery callback


How to get a 'MyClass' instance in the callback from jquery.

function MyClass(){      

  this.message = 'Hello World'; // I need access to this variable in the callback

  //registering class member function as callback
  $('div').draggable({drag:this.onDrag});

  this.onDrag = function(event,ui){

   alert(this.message); // 'this' is jquery object, not MyClass instance;

  }
}

P.S. Global variable with 'MyClass' instance or storing instance into data is not desirable.

Thank you!


Solution

  • The best option here (IMO) is just to keep another reference, I prefer self, like this:

    function MyClass(){      
      var self = this;
      this.message = 'Hello World'; // I need access to this variable in the callback
    
      //registering class member function as callback
      $('div').draggable({drag:this.onDrag});
    
      this.onDrag = function(event,ui){    
        alert(self.message);
      }
    }
    

    The alternative is messing with context of another plugin you don't really control when (again, IMO) it's not really necessary, just having another reference to access your class is just as easy and less confusing in many cases.