0

After I instantiate my class, I call myClass.testScope(), which calls another function inside the class. But, when I pass the function as a parameter, I lose scope and calling testScopeFromPassedParam from data1 results in the error Uncaught TypeError: Object [object global] has no method 'testScopeFromPassedParam'

Can someone please aid in the best way to handle this?

http://jsfiddle.net/2sJVX/4/

class MyClass

  test: () ->

    @testScope()

  testScope: () ->

    console.log 'worky'

  testScopeFromPassedParam: () ->

    console.log 'no worky'

  data1: (cb) ->

    # Shoot. The error.
    @testScopeFromPassedParam()

    setTimeout (->
      cb '1'
    ), 1000

  data2: (cb) ->
    setTimeout (->
      cb '2'
    ), 3000

  loadData: () ->

    getDeferred = (someFunction) ->

      deferred = $.Deferred()

      someFunction (data) ->

        console.log data

        deferred.resolve()

      deferred

    dataFunctions = [
      @data1
      @data2
    ]

    arrayOfPromises = [ ]
    for someFunction in dataFunctions
      arrayOfPromises.push getDeferred(someFunction)

    $.when.apply(null, arrayOfPromises).done () =>
      alert 'returned'

myClass = new MyClass()
myClass.testScope()
myClass.loadData()
1
  • Usually that sort of thing is handled by creating a reference in a closure scope, but not sure how such a solution would work in coffeescript. Commented Mar 20, 2013 at 22:22

1 Answer 1

1

That's not [variable] scope, that's the this context which is lost here. You will need to bind the function to your object, in coffeescript you can use the fat-arrow syntax for this:

data1: (cb) =>
    @testScopeFromPassedParam()
    …

Btw, you really should pass on the data to the resolve function (or just use somefunction deferred.resolve)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Yes, terminology was wrong. Can you explain what you mean by "I really should pass on the data to the resolve function", please? I'm missing it :)
You call deferred.resolve() with nothing, but you should do deferred.resolve(data) otherwise the promise doesn't get the value :-)
Ahh, that makes sense. This exercise was really about learning about $.when and deferreds, then I ran into this issue. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.