state

state (GitHub: nickfargo/state, License: MIT) is a library for implementing first-class states on arbitrary owner objects.

1
npm install state

There’s an incredible amount of funtionality described in the very extensive documentation.

Minimal footprint

All functionality of State is to be instigated through the exported state function. It should be able both to generate state expressions and to implement expressed states into an existing JavaScript object, depending on the arguments provided. In the latter case, the newly implemented system of states should be accessible from a single object. state() method on the affected object.

Expressive power

As much as possible, State should aim to look and feel like a feature of the language. The interpreted shorthand syntax, simple keyword attributes, and limited interface should allow for production code that is terse, declarative, and easy to write and understand.

Opacity

Apart from the addition of the object.state() method, a call to state() must make no other modifications to a State–affected object’s interface. Methods are replaced with delegators, which forward method calls to the current state. This is to be implemented opaquely and non-destructively: consumers of the object need not be aware of which states are active in the object, or even that a concept of state exists at all, and a call to object.state('').destroy() must restore the object to its original form.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var flavors = [
  'vanilla',
  'chocolate',
  'strawberry',
  'AmeriCone Dream'
];
function Kid () {}
state( Kid.prototype, 'mutable', {
  data: {
    favorite: 'chocolate'
  },
  waver: state.bind( function () {
    var i = Math.random() * flavors.length << 0;
    this.data({ favorite: flavors[i] });
  }),
  whine: function ( complaint ) {
    if ( typeof console !== 'undefined' ) {
      console.log( complaint );
    }
  },
  mutate: function ( mutation, replaced ) {
    this.owner().whine(
      "I hate " + replaced.favorite + ", " +
      "I want " + mutation.favorite + "!"
    );
  }
});
var jr = new Kid;
jr.waver();  // log <<< "I hate chocolate, I want strawberry!"
jr.waver();  // log <<< "I hate strawberry, I want chocolate!"
jr.waver();  // nothing
jr.waver();  // log <<< "I hate chocolate, I want AmeriCone Dream!"

There are plenty of examples and information on the documentation site. Check it out!

Post navigation

Leave a comment

Leave a Reply

Your email address will not be published.