0

I am trying to create a statechart framework as a sparetime project.

CoffeeScript

Statechart.state "A", ->
  @state "B1", ->
    @state "C"
  @state "B2", ->

JavaScript

Statechart.state("A", function() {
  this.state("B1", function() {
    this.state("C");
  });
  this.state("B2", function() {
  });
});

I wonder if there is a way for the inner functions to be aware of the outer one, so that B1 and B2 know they are children of A and C knows it is a child of B1.

UPDATE: I used bind(). It worked great!

ajsie
  • 77,632
  • 106
  • 276
  • 381

3 Answers3

1

Use the fat arrow =>. It uses an implementation of Function.prototype.bind:

Statechart.state "A", ->
   @state "B1", =>
       @state "C"
   @state "B2", =>

In this code, @/this will always refer to the Statechart object.

Ricardo Tomasi
  • 34,573
  • 2
  • 55
  • 66
0

I wrote one that is pretty full featured in straight javascript. Stativus. You can use that as a model to implement it in CoffeeScript.

Keep me up to date if you need help or have questions.

etgryphon
  • 166
  • 1
  • 5
0

You need to hold a reference to the value of 'this/@' inside the first function.

I would usually create a variable called 'self' as below:

Statechart.state "A", ->
   self = @
   @state "B1", ->
       self.state "C"
   @state "B2", ->
Adam Hutchinson
  • 264
  • 3
  • 12
  • Sorry for not being specific. That is the API the users will use. The end result can't be altered. I wanna know how I could have the functions to be aware of the hierarchy behind the scenes. Someone told me to use bind(), I think that might work. – ajsie Nov 18 '11 at 16:42
  • 1
    [this](http://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript/4047670#4047670) from @Francisco Soto's answer looks like it could be relevant. – Adam Hutchinson Nov 18 '11 at 16:44