Adinan
Adinan

Reputation: 135

Coffeescript Undefined class?

I am starting with coffeescript. (And english as well, so I'm sorry about any grammatical error.) Look at this class:

class Stuff
  handleStuff = (stuff) ->
    alert('handling stuff');

It compiles to :

var Stuff;
Stuff = (function() {
  var handleStuff;

  function Stuff() {}

  handleStuff = function(stuff) {
    return alert('handling stuff');
  };

  return Stuff;

})();

on Html I created an instance of Stuff, but the damn thing say it has no method handleStuff. Why?

Upvotes: 3

Views: 719

Answers (1)

vcsjones
vcsjones

Reputation: 141638

You want handleStuff to be on the prototype, so change it to this:

class Stuff
  handleStuff: (stuff) ->
    alert('handling stuff');

The difference is a colon vs. an equals.

Which compiles to:

var Stuff;

Stuff = (function() {
  function Stuff() {}

  Stuff.prototype.handleStuff = function(stuff) {
    return alert('handling stuff');
  };

  return Stuff;

})();

You can see it working here:

<script src="http://github.com/jashkenas/coffee-script/raw/master/extras/coffee-script.js"></script>
<script type="text/coffeescript">
class Stuff
  handleStuff: (stuff) ->
    alert('handling stuff');
    
stuffInstance = new Stuff()
stuffInstance.handleStuff()
</script>

And more information on classes and class members in the documentation.

Upvotes: 5

Related Questions