Getting class instance from jquery callback

How to get instance of MyClass in 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;

  }
}

PS A global variable with an instance of "MyClass" or storing an instance in data is undesirable.

Thank!

+3
source share
1 answer

The best option here (IMO) is to simply save another link, I prefer self, for example:

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 conflicts with the context of another plugin that you really don't control when (again, IMO) you really don't need it, just having another link to access your class is just as easy and less confusing in many cases.

+4
source

Source: https://habr.com/ru/post/1776407/


All Articles