Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing class member variables inside an event handler in Javascript

I have a quick question regarding the proper way to access Javascript class member variables from inside of an event handler that class uses. For example:

function Map() {     this.x = 0;     this.y = 0;      $("body").mousemove( function(event) {         this.x = event.pageX;     // Is not able to access Map's member variable "x"         this.y = event.pageY;     // Is not able to access Map's member variable "y"     }); } 

Rather than changing the member variable of the "Map" class, the "this.x" in the event handler tries to affect the "x" member variable of the element that triggered the event. What is the proper way to access the member variables of the "Map" class from within the event handlers?

Any help would be greatly appreciated - I've been sort of scratching my head at this one.

Cheers, Charlie

like image 266
zeptonaut Avatar asked Jun 19 '10 15:06

zeptonaut


People also ask

How do you access member variables in a class?

To access class variables, you use the same dot notation as with instance variables. To retrieve or change the value of the class variable, you can use either the instance or the name of the class on the left side of the dot.

Which of the three JavaScript functions are event handlers?

There are three ways to assign an event handler: HTML event handler attribute, element's event handler property, and addEventListener() .

How do event handlers work in JavaScript?

JavaScript Event HandlersEvent handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.

Can you add event listeners to classes?

To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements.


1 Answers

Since this changes in an event context (points to global usually), you need to store a reference to yourself outside of the event:

function Map() {     this.x = 0;     this.y = 0;     var _self = this;     $("body").mousemove( function(event) {         _self.x = event.pageX;     // Is now able to access Map's member variable "x"         _self.y = event.pageY;     // Is now able to access Map's member variable "y"     }); } 
like image 191
Matt Avatar answered Sep 18 '22 22:09

Matt