Don Giulio
Don Giulio

Reputation: 3304

instance variables and constants in coffeescript classes

I'm trying to define a class in coffeescript, to use it in my rails project. I'm struggling with the syntax for defining CLASS constants and referring to them, this is what I have so far:

class Project

  inputFields :
    title: '#title'

  calculateDataList : [
    @inputFields.title
  ]

but the browser complains with:

Uncaught TypeError: Cannot read property 'title' of undefined

I'm not sure what would be the right syntax here. could anyone help me?

thanks,

Upvotes: 1

Views: 1434

Answers (3)

edi9999
edi9999

Reputation: 20574

In fact, your code doesn't compile.

I'm not sure what you want, but this coffeescript code:

class Project

    inputFields :
        title: '#title'

    calculateDataList : [@inputFields.title]

compiles to the following Javascript:

// Generated by CoffeeScript 1.6.3
(function() {
  var Project;

  Project = (function() {
    function Project() {}

    Project.prototype.inputFields = {
      title: '#title'
    };

    Project.prototype.calculateDataList = [Project.inputFields.title];

    return Project;

  })();

}).call(this);

Upvotes: 0

Powers
Powers

Reputation: 19348

This is the basic syntax for a CoffeeScript class:

class Add
  constructor: (number1, number2) ->
    @number1 = number1
    @number2 = number 2

  run: ->
    @number1 + @number2

I think something like this will work for your code:

class Project
  inputFields: ->
    title: '#title'

  calculateDataList: ->
    [this.inputFields().title]

Project is a class and inputFields() and calculateDataList() are methods. To call the inputFields() method in calculateDataList(), use the this keyword.

Run the code with this command:

p = new Project
p.calculateDataList() 

Upvotes: 1

mikach
mikach

Reputation: 2427

You must save reference to prototype. Try this one:

class Project

  inputFields :
    title: '#title'

  calculateDataList : [
    Project::inputFields.title
  ]

Upvotes: 1

Related Questions