Andrew Ingram
Andrew Ingram

Reputation: 5220

Calling class function within a constructor isn't being recognised

Answer:

It turns out I had neglected to use the new keyword when creating the class instance. The code in the question itself is fine.

Question:

I have a fairly simple class where the constructor calls another method on the class (editor_for_node). The call happens inside a jQuery each() loop, but I've also tried moving it outside.

define ['jquery'], ($) ->
  class Editor
    constructor: (@node, @data, @template) ->
      @node.widgets().each (i, elem) =>
        data = if @data then @data[i] else null
        node = $(elem)
        @editor_for_node node, data

    editor_for_node: (node, data) ->
      console.log 'hello!'

  return {
    'Editor': Editor,
  }

When the line @editor_for_node node, data gets called, I get an error (in Firebug) saying this.editor_for_node is not a function.

I really can't see why this isn't working properly, the only possible source of weirdness that I can see is my use of require.js's define function at the start.

Edit: Generated output

(function() {

  define(['jquery'], function($) {
    var Editor;
    Editor = (function() {

      Editor.name = 'Editor';

      function Editor(node, data, template) {
        var _this = this;
        this.node = node;
        this.data = data;
        this.template = template;
        this.node.widgets().each(function(i, elem) {
          data = _this.data ? _this.data[i] : null;
          node = $(elem);
          return _this.editor_for_node(node, data);
        });
      }

      Editor.prototype.editor_for_node = function(node, data) {
        return console.log('hello!');
      };

      return Editor;

    })();
    return {
      'Editor': Editor
    };
  });

}).call(this);

Upvotes: 2

Views: 1487

Answers (1)

Trevor Burnham
Trevor Burnham

Reputation: 77416

First: Which version of CoffeeScript are you using? The fat arrow has been a source of bugs in certain previous releases.

If you're using the latest (1.3.1), then I'm going to go ahead and say that this is an indentation issue. When I copy and paste your code, it works fine. Are you mixing tabs and spaces? Verify that the compiled output contains the line

Editor.prototype.editor_for_node = ...

Update: See the comments on this answer. Turns out the problem was that the new keyword wasn't being used when invoking the constructor.

Upvotes: 4

Related Questions