So im running into a bit of confusion on "this" in event handlers and properly preserving them. I have done a good bit of googling and have figured out "Why" this is changing when calling an element......but not really a way to fix it for my situation.
I've set up a sample concept here: https://jsfiddle.net/msmith1114/xu4zbppz/8/
You've got two buttons and a simple class. The main part im concerned about is setting up the jquery event handlers for these buttons in my class prototype (I've posted a separate question about where event handlers should "usually" go when referring to javascript classes here: ES6 Classes/Object oriented and Event Handlers)
and one of the answers does go into a little detail on "this" and it makes sense.
Just looking at the class:
class Player {
constructor() {
$(".demo").click(function() {
console.log(this)
console.log($(this).text())
});
this.color
this.name = 'Player 1'
}
printName(player) {
if (player == 1)
console.log(this.name + "'s color is " + this.color)
}
}
ER, how can I set an event handler for constructor items on clicks. IE what if I want to store the this.color
(for the player class) equal to the button.text()
value? If I bind $(this)
then I can't refer to the button text....however if I don't bind it, I can't really store it since I can't really say in the event handler this.color = $(this).text()
as great as it would be if that worked.
Or is this just straight up bad practice? Im just starting this classes and really diving into Object Oriented javascript...and I learned a lot about this
and object creation, but when it came to implementing it into DOM related JS code I didn't really know where to put my event handlers. (Such as in a tic-tac-toe game, i've created a "board" class so it seems to me the event handlers would be in the "board" class itself....am I going about this the wrong way?
Or is there a workaround that makes sense. I've seen some examples that assign the click event handler to variables....but im not sure I understand the point of that (they were mostly non-jquery code anyways).