Adding event listeners to the constructor

function Foo(elementId, buttonId) { this.element = document.getElementById(elementId); this.button = document.getElementById(buttonId); this.bar = function() {dosomething}; this.button.addEventListener('click', function(e) {this.bar();}, false); } var myFoo = new Foo('someElement', 'someButton'); 

I would like to add event listeners to my constructor, but it does not work. Is this possible with the correct syntax? I always hung on the line:

 this.button.addEventListener('click', function(e) {this.bar();}, false); 
+6
source share
3 answers

Your this value changes in the constructor. You can save the link in the selector and use the link.

 function Foo(elementId, buttonId) { /*...*/ var self = this; this.button.addEventListener('click', function(e) {self.bar();}, false); } 

Or a more modern solution that does not require a variable would use Function.prototype.bind .

 function Foo(elementId, buttonId) { /*...*/ this.button.addEventListener('click', this.bar.bind(this), false); } 

The .bind method returns a new bar function with the this value associated with the fact that you passed it. In this case, it is bound to the original this from the constructor.

+5
source

this in the event handler is the element into which the event was added.

To access the external this , you need to store it in a separate variable.

+1
source

this in the click handler is the button element, not the object, use a variable to refer to the object, for example var self = this;

 function Foo(elementId, buttonId) { var self = this; this.element = document.getElementById(elementId); this.button = document.getElementById(buttonId); this.bar = function() {dosomething}; this.button.addEventListener('click', function(e) {self.bar();}, false); } 
0
source

Source: https://habr.com/ru/post/926963/


All Articles