简体   繁体   English

从jquery回调中获取类实例

[英]Getting class instance from jquery callback

How to get a 'MyClass' instance in the callback from jquery. 如何在jquery的回调中获取'MyClass'实例。

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 Global variable with 'MyClass' instance or storing instance into data is not desirable. 带有“MyClass”实例的PS全局变量或将实例存储到数据中是不可取的。

Thank you! 谢谢!

The best option here (IMO) is just to keep another reference, I prefer self , like this: 这里最好的选择(IMO)只是为了保留另一个参考,我更喜欢self ,像这样:

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. 另一种方法是搞乱另一个你并不真正控制的插件的上下文(再次,IMO)它并不是真的有必要,只是有一个访问你的类的另一个参考就像在许多情况下一样容易和不那么混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM