1

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,

4

3 回答 3

1

您必须保存对原型的引用。试试这个:

class Project

  inputFields :
    title: '#title'

  calculateDataList : [
    Project::inputFields.title
  ]
于 2013-07-23T13:38:57.550 回答
1

这是 CoffeeScript 类的基本语法:

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

  run: ->
    @number1 + @number2

我认为这样的事情将适用于您的代码:

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

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

Project是一个类,inputFields()并且calculateDataList()是方法。要调用 中的inputFields()方法calculateDataList(),请使用this关键字。

使用以下命令运行代码:

p = new Project
p.calculateDataList() 
于 2013-07-23T13:34:07.497 回答
0

实际上,您的代码无法编译。

我不确定你想要什么,但是这个咖啡脚本代码:

class Project

    inputFields :
        title: '#title'

    calculateDataList : [@inputFields.title]

编译为以下 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);
于 2013-07-23T14:27:18.527 回答