从 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 具有“MyClass”实例的全局变量或将实例存储到数据中是不可取的。
谢谢你!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里最好的选择(IMO)只是保留另一个引用,我更喜欢
self
,如下所示:另一种选择是混淆另一个你无法真正控制的插件的上下文(再次,IMO)它是并不是真正必要,在许多情况下,只需使用另一个引用来访问您的类就同样容易且不那么混乱。
The best option here (IMO) is just to keep another reference, I prefer
self
, like this: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.