我有一个 ajax 调用,它通过点击我的控制器来获取一些 JSON:
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)))
问题是我从一开始就需要玩家,并且看到 JS 是如何异步运行的,变量是空的。有没有一种方法可以用 ajax 调用实际初始化变量?
更新:在从@mu_is_too_short 对问题有了新的看法并理解了从@Rich Peck 进行ajax 调用时回调的真正重要性之后,我能够通过确保依赖于从返回的数据的所有代码来初始化我的游戏Ajax 调用包含在 Ajax 成功回调中。我认为我可能必须包含构建游戏所需的所有数据,而不仅仅是团队和玩家数据。但那是以后了。多谢你们。
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