Jamie Fearon
Jamie Fearon

Reputation: 2634

Instance variable becomes undefined - CoffeeScript

class Game

  foo: null

  play: ->

    @foo = 2
    @animate()

  animate: ->

    requestAnimationFrame( @animate, 1000 )
    console.log('foo = ', @foo)


$ ->
  game = null

  init = ->

    game = new Game()
    game.play()

  init()

The log in the animate method in Game produces:

foo = 2

foo = undefined

So foo is 2 on the first call to animate and then undefined thereafter. Could someone please explain why and how I can fix this. Any help is much appreciated.

Upvotes: 5

Views: 1405

Answers (2)

yfeldblum
yfeldblum

Reputation: 65435

You can define animate as follows:

animate: ->
  callback = (=> @animate())
  requestAnimationFrame(callback, 1000 )
  console.log('foo = ', @foo)

The technique here is to get a bound method. @animate by itself is unbound, but (=> @animate()) is the bound version of it.

You can get a similar results if you're using UnderscoreJS as follows:

animate: ->
  callback = _.bind(@animate, @)
  requestAnimationFrame(callback, 1000 )
  console.log('foo = ', @foo)

And if you are using a later version of JavaScript, you may be able to do as follows:

animate: ->
  callback = @animate.bind(@)
  requestAnimationFrame(callback, 1000 )
  console.log('foo = ', @foo)

Upvotes: 5

Aaron Dufour
Aaron Dufour

Reputation: 17505

When you call setInterval, context is lost and the second time @ is window. You need fat-arrow methods to retain the appropriate this:

animate: =>

Upvotes: 11

Related Questions