Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

A simple JavaScript state machine with observers, for browsers and Node.js.

branch: master
README.md

Skinny Coffee Machine endorse Build Status

A simple JavaScript state machine with observers, for browsers and Node.js.

Skinny Coffee Machine is a simple JavaScript state machine written in CoffeeScript. It is being developed for the 2.0 rewrite of jQuery Endless Scroll.

NPM

If you use npm, you can grab the source code by:

npm install skinny-coffee-machine

Usage

Define State Machines

@coffeeMachine.power = new SkinnyCoffeeMachine
  default: 'off'
  events:
    turnOn:
      off: 'on'
    turnOff:
      on: 'off'
  on:
    turnOn:  (from, to) -> "#{from.toUpperCase()} to #{to.toUpperCase()}"
    turnOff: (from, to) -> "#{from.toUpperCase()} to #{to.toUpperCase()}"
  before:
    turnOff: (from, to) -> "Before switching to #{to.toUpperCase()}"
  after:
    turnOn:  (from, to) -> "After switching to #{to.toUpperCase()}"
    turnOff: (from, to) -> "After switching to #{to.toUpperCase()}"

@coffeeMachine.mode = new SkinnyCoffeeMachine
  default: 'latte'
  events:
    next:
      latte: 'cappuccino'
      cappuccino: 'espresso'
      espresso: 'lungo'
      lungo: 'latte'
    last:
      latte: 'lungo'
      lungo: 'espresso'
      espresso: 'cappuccino'
      cappuccino: 'latte'

Switch/Change States

You may use either switch or change for switching states:

@coffeeMachine.power.currentState() #=> "off"

@coffeeMachine.power.switch('turnOn')

@coffeeMachine.power.currentState() #=> "on"

To change states multiple times:

@coffeeMachine.mode.currentState() #=> "latte"

@coffeeMachine.mode.change('next', 3)

@coffeeMachine.mode.currentState() #=> "cappuccino"

Observers

In order to provide more flexibility on state transition callbacks, you may use observers to dynamically add and remove events.

To start observing:

@coffeeMachine.power.observeBefore('turnOn').start 'labelA', (from, to) => "Observer A before switching to #{to.toUpperCase()}"
@coffeeMachine.power.observeOn(    'turnOn').start 'labelB', (from, to) => "Observer B on switching to #{to.toUpperCase()}"
@coffeeMachine.power.observeAfter( 'turnOn').start 'labelC', (from, to) => "Observer C after switching to #{to.toUpperCase()}"

To stop observing:

@coffeeMachine.power.observeBefore('turnOn').stop('labelA')

Contribute

Skinny Coffee Machine uses Grunt, PhantomJS and Mocha.

After you have Grunt and PhantomJS set up, you may run tests by:

grunt

To automatically compile CoffeeScript as well as run tests during development, you may use:

grunt watch

License

Copyright (c) 2012 Fred Wu

Licensed under the MIT license.

Bitdeli Badge

Something went wrong with that request. Please try again.