Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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", ->

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top