I am trying to use the methods from a javascript constructor as event handlers, and also access the id attribute of the DOM element that the handler is bound to. I know that once the event listener and associated callback function have been attached to a DOM element the value of "this" inside the callback function will point to that DOM element and not the constructor where the function was defined. So, how can I call the methods defined in my js constructor from an event handler? Currently when I click an element I get the error,
Uncaught TypeError: Cannot read property 'setOpponent' of undefined
This is the the code that is not working, and here is a link to my full project on codepen.
function DOM(){
/*store references to DOM elements*/
}
function Board(){
/*props and methods to keep track of open/occupied squares*/
}
function Game(){
this.dom = new DOM();
this.board = new Board();
/*props and methods for the game*/
this.attachEventHandlers = function(){
$(this.dom.$opponentOption).on("click", function(){
var opponent = $(this).attr("id");
this.setOpponent(opponent).bind(this);
});
$(this.dom.$characterOption).on("click", function(){
var character = $(this).attr("id");
this.setCharacter(character).bind(this);
});
$(this.dom.$square).on("click", function(){
var square = $(this).attr("id");
this.squareClickHandler(square).bind(this);
})
$(this.dom.$reset).on("click", function(){
this.resetGame().bind(this);
});
};
}
var game = new Game();
game.attachEventHandlers();