Reputation: 3011
I made a simple game yesterday in javascript using coffeescript. The bulk of the game runs through a game
object which is instantiated after the user submits a form on the page. The form contains variables and options for the game they want to play.
Everything works fine during the game, but when the game is over I have the form appear again and if the user submits the form a second time its supposed to call the same function and overwrite the old game
variable with a new instance of the game
object, but what I've noticed is that its not resetting all the existing variables and paramaters set by the original game object.
Is there any way to fully remove the old object and its parameter when a new one is instantiated?
Here is My object being declared as a 'class' in coffeescript.
window.Game = class Game
constructor: (options) ->
players = options[0] ? '1'
p1 = p2 = false
@player1 = new Player(options[1] ? 'X', p1 )
@player2 = new Player(options[2] ? 'O', p2 )
@cells = ($ "section#board .cell")
@cells.each ->
$(@).text(" ")
$(@).removeClass('score')
@currentPlayer = @player1
@availableMoves = 9
($ 'section#board div.cell').bind
click: @.makeMove
mouseleave: @.resetCell
setTimeout(@.computerMove(@currentPlayer), 1000) if parseInt(players) is 0
I'm calling this after form submit through this function.
($ '#gameOptions').submit (event) ->
event.target.checkValidity()
event.preventDefault()
game = new Game [($ '#player-count') .val(),
($ '#player-1-type').val(),
($ '#player-2-type').val()]
Even when adding a call do delete game
before re-instantiating the game object. The ghost variables persist. I posted in coffeescipt for brevity and to increase readability.
Upvotes: 0
Views: 456
Reputation: 17535
The delete game
will not remove the object, only the reference. The problem is that references to the old variable are persisting somewhere. There might be others, but at the very least this part of the constructor is giving you problems:
($ 'section#board div.cell').bind
click: @.makeMove
mouseleave: @.resetCell
JQuery is allowing you to bind multiple functions to the same event; in this case, both the old and new functions, and the old ones are holding the reference to the old object. In order to fix this, you should unbind in the form submission function:
($ 'section#board div.cell').unbind()
Upvotes: 1