user375566
user375566

Reputation:

Scope issue with passing function as parameter

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()

Upvotes: 0

Views: 273

Answers (1)

Bergi
Bergi

Reputation: 665456

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)

Upvotes: 1

Related Questions