[英]How to listen to the events inside an object?
I am trying to listen to a click event and give the output accordingly. 我正在尝试收听点击事件并相应地提供输出。
However, I am a bit confuse on adding events inside an object. 但是,我在对象中添加事件有点混乱。
I tried this. 我试过这个。
var object1 = {
getVariables: {
button1: document.getElementById('button');
},
eventHandler: {
getVariables.button1.addEventListener('click', this.alertSomething);
},
alertSomething: function() {
alert('Cool');
}
};
Is this a correct way to listen to the events? 这是听听事件的正确方法吗? If not, please help me correct it. 如果没有,请帮我纠正。
You'll have to save the reference to the variable somewhere in the object - and for the object to reference itself to achieve that, it'll have to use this
somehow. 你必须在对象的某个地方保存对变量的引用 - 并且对象要引用它来实现它,它必须以某种方式使用this
。 (well, you could also pass in the whole object as a separate argument, but that's kinda odd and not often done) (好吧,你也可以将整个对象作为一个单独的参数传递,但这有点奇怪而且不经常这样做)
It's somewhat tricky because when calling object1.getVariables.button1
, the context of this
is the object referenced by the getVariables
property, but you likely want to put the information into somewhere more appropriate within object1
itself, not within getVariables
. 这有点棘手,因为当调用object1.getVariables.button1
的背景下, this
是由引用的对象getVariables
属性,但你可能希望把信息转化为内某处更合适object1
本身,而不是内getVariables
。 Let's store the variables in a storedVariables
property. 让我们将变量存储在storedVariables
属性中。
We want the functions to be called with a reference to the outer object, not the getVariables
or addEventHandler
property, so we have to use call
to pass a custom this
to the functions: 我们要的功能与对外部对象的引用调用,而不是getVariables
或addEventHandler
属性,所以我们必须使用call
通过自定义this
的职能:
const button = document.getElementById('button'); const object1 = { storedVariables: {}, getVariables: { button1: function() { this.storedVariables.button1 = document.getElementById('button') }, }, addEventHandler: { button1: function() { this.storedVariables.button1.addEventListener('click', this.alertSomething); }, }, alertSomething: function() { alert('Cool'); } }; object1.getVariables.button1.call(object1); object1.addEventHandler.button1.call(object1);
<div id="button"> some button </div>
It would be notably less convoluted if there was a method such as getButton1
directly on object1
(and the same for addEventHandler
), that way they could be called normally without having to customize their this
. 如果有,如方法这将是特别少令人费解的getButton1
直接object1
(与同为addEventHandler
),这样,他们可以被正常,而无需定制自己叫this
。
Just bind object1
object to this
variable. 只需将object1
对象绑定this
变量即可。
<!DOCTYPE html> <html> <body> <div id="button1"> Button-1 </div> <script> var object1 = { button1: document.getElementById('button1'), eventHandler: function() { this.button1.addEventListener('click', this.alertSomething); }, alertSomething: function() { alert('Cool'); } }; object1.eventHandler.call(object1); </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.