I've been learning the ins and outs of JavaScript and Object Oriented/Functional programming instead of writing hacky imperative code that while works....just is ugly and honestly not efficient.
I was re-writing a tic-tac-toe game and am using Classes to implement the "Board" functions (Updating the board/checking tiles/etc...)
and I realized.....where on earth should I be putting Event listeners (for buttons/tiles/etc...) in the page. I usually just put jquery .click
functions in the document.ready
scope, but that doesn't seem right.
When I create a class with new
would event listeners get attached or "readied"....I guess maybe I mis-understand how listeners work. And if they would work within a class as functions/methods? Or if it even makes sense to attach them there.
For instance here is my base class right now (it's literally just set up so it's like bare minimum.
"use strict";
class Board
{
constructor(playerIcon,compIcon) {
this.playerIcon = playerIcon;
this.compIcon = compIcon;
});
}
getTileContents(tile){
return $("#tile-" + tile).text()
}
tileIsEmpty(tile){
console.log($("#tile-" + tile).text())
if($("#tile-" + tile).text() != 'X' || $("#tile-" + tile).text() != 'Y')
return true
else
return false
}
}
let board = new Board('X','Y');
I thought maybe attaching the event listeners in the constructor would work? Since the constructor will be instantiated when new is called at least correct?
Maybe it's just my misunderstand of how event handlers are handled or "bound" exactly?
edit: Here is my pitiful tic-tac-toe so far for reference: http://codepen.io/msmith1114/pen/qmNevg
(This is what im talking about in regards to the board)