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. (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
. Let's store the variables in a storedVariables
property.
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:
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
.
Just bind object1
object to this
variable.
<!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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.