如何访问 Mootools fireEvent 函数的第二个参数中的对象实例?
我正在 Mootools 中使用实现:[事件、选项]。
我想将类属性传递给事件触发时调用的函数。我本以为我可以使用 this 来做到这一点,但 this 未定义。
我已经评论了下面我的问题所在的代码。我有一种感觉,这可能与绑定有关,所以我现在就看一下。预先感谢您的任何帮助!
var Person = new Class({
Implements: [Options, Events],
initialize: function(options){
this.setOptions(options);
}
});
greet = function(name){
log('Hello, I am ' + name);
}
var ryan = new Person({
name: 'Ryan',
onArrive: greet //add event 'arrive'
});
ryan.fireEvent('arrive', ryan.options.name); //ideally I would use this.options.name?
这段代码可以工作,但在最后一行中使用对象实例名称而不是 this 似乎很奇怪。
I'm working through Implements: [Events, Options] in Mootools.
I would like to pass a class property to the function that is called when an event fires. I would have thought that I could do it using this but this is undefined.
I have commented the code below where my problem is. I have a feeling that this might be to do with binding so I will be having a look at that now. Thanks in advance for any help!
var Person = new Class({
Implements: [Options, Events],
initialize: function(options){
this.setOptions(options);
}
});
greet = function(name){
log('Hello, I am ' + name);
}
var ryan = new Person({
name: 'Ryan',
onArrive: greet //add event 'arrive'
});
ryan.fireEvent('arrive', ryan.options.name); //ideally I would use this.options.name?
This code works but it just seems strange to use the object instance name instead of this in the last line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您触发事件时,此是您的 ryan 实例。
要使其工作,只需进行以下更改
,但由于现在问候语取决于实例,因此最好将其包含在您的类定义中
,并且
When you fire the event this is your instance of ryan.
To make it work just make the following changes
but since greet now depends on the instance it would be better to include it in your class definition
and
this
关键字指的是当前对象。在您的情况下,this
可能指的是全局对象(窗口)。您必须位于ryan
实例范围内,以便可以将ryan
引用为this
:您还可以重载
fireEvent< /code> 方法(如果您不想再次使用对同一实例的引用)。像这样的东西:
然后这样称呼它:
the
this
keyword refers to the current object. In your case,this
probably refers to the global object (window). You have to be in theryan
instance scope so that you can refer toryan
asthis
:You could also overload the
fireEvent
method if you don't want to use a reference to the same instance again. Something like this :and then call it like this :