Don Giulio
Don Giulio

Reputation: 3284

coffeescript, class undefined variable.

I don't quite understand the syntax in coffeescript for defining an instance variable.

here's my scenario: I have an initializer and two classes, Calculations and Controller, Controller uses an instance of Calculations internally.

Here's the code:

initializer block

$ ->
  calc = new Calculations()
  log "initcalc: #{calc}"
  tc = new Controller(calc)
  tc.initForm()

where the log prints correctly: initcalc: [object Object]

the Class Calculations is defined as follows:

class Calculations
  constructor: ->
  updateFields: -> 
    log "updateFields"

the Class Controller is defined as:

class Controller
  constructor: (calc) ->
  initForm: -> 
    log "calc : #{@calc}"
    @calc.updateFields()

the init form is called by the initializer right after instantiating the classes here's it's output:

calc : undefined trade_class_new.js?body=1:8
Uncaught TypeError: Cannot call method 'updateFields' of undefined

I don't understand how's the syntax for an instance variable in coffeescript.

thanks,

Upvotes: 0

Views: 149

Answers (2)

Menztrual
Menztrual

Reputation: 41587

The controller constructor needs to be (@calc) instead of (calc)

Upvotes: 1

sbking
sbking

Reputation: 7680

You need to change your Controller constructor to:

constructor: (@calc) ->

Otherwise it's just taking a calc parameter and doing nothing with it.

Upvotes: 2

Related Questions