I have an ajax call that fetches some JSON by hitting my controller:
class @Team
constructor: () ->
@players = null
@getTeamInfo()
getTeamInfo:(teamId) ->
request = $.ajax
dataType: 'json',
type: 'GET'
url: "http://localhost:4000/teams/#{teamId}",
async: false
success : (data) =>
_.each(data.players, (value) ->
name = _.pluck(value, 'name')
@players.push(new Player(name)))
The problem is that I need the players from the very start, and, seeing how JS runs asynchronously, the variables are null. Is there a way I can actually initialize variables with an ajax call?
UPDATE: After getting a new perspective on the issue from @mu_is_too_short and understanding the real importance of callbacks when doing ajax calls from @Rich Peck, I was able to get my game initializing by ensuring that all the code that depended on the data returned from the Ajax call was included in the Ajax success callback. I think I may have to include all the data that I will need to build the game, not just the team and player data. But that's later. Thanks, guys.
class @Game
constructor: (homeId, awayId) ->
@homeTeam = new Team()
@awayTeam = new Team()
@display = new GameDisplay()
@pitcher = new Pitching()
@contact = new Contact()
@baseRunners = new BaseRunners()
@gameEngine = new GameEngine(@homeTeam, @awayTeam, @display, @pitcher, @contact, @baseRunners)
@initializeHomeBattingOrder(1, 3)
pitch: ->
@gameEngine.makePitch()
initializeHomeBattingOrder: (homeId, awayId) ->
$.ajax
dataType: 'json',
type: 'GET',
url: "http://localhost:4000/teams/#{homeId}",
success : (data) =>
@populateHomePlayers(data)
@initializeAwayBattingOrder(awayId)
initializeAwayBattingOrder: (awayId) ->
$.ajax
dataType: 'json',
type: 'GET',
url: "http://localhost:4000/teams/#{awayId}",
success : (data) =>
@populateAwayPlayers(data)
@display.battingOrder(@awayTeam.players, @homeTeam.players)
@display.teamsPlaying(@awayTeam.name, @homeTeam.name)
populateHomePlayers: (data) ->
@homeTeam.players = _.map(_.pluck(data.players, "name"), (name) -> new Player(name))
@homeTeam.name = data.name
populateAwayPlayers: (data) ->
@awayTeam.players = _.map(_.pluck(data.players, "name"), (name) -> new Player(name))
@awayTeam.name = data.name