4

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!

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, this is really simple solution for that. Thank you very much Nick!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.