ConstraintJS API

cjs(...)

cjs is ConstraintJS's only visible object; every other method an property is a property of cjs. The cjs object itself can also be called to create a constraint object.

cjs(value, options)
valueobjectA map of initial values
optionsobjectA set of options to control how the array constraint is evaluated
Returnscjs.ArrayConstraintA new array constraint
cjs(node)
nodedomThe DOM node whose value to follow
Returnscjs.BindingA constraint whose value is the current value of the input
cjs(value, options)
valueobjectA map of initial values
optionsobjectA set of options to control how the map constraint is evaluated
Returnscjs.MapConstraintA new map constraint
cjs(value, options)
valueobjectThe constraint's value
optionsobjectA set of options to control how the constraint is evaluated
Returnscjs.ConstraintA new constraint

Example:

Creating an array constraint

var cjs_arr = cjs([1,2,3]);
    cjs_arr.item(0); // 1

Creating an input value constraint

var inp_elem = document.getElementById('myTextInput'),
    cjs_val = cjs(inp_elem);

Creating a map constraint

var cobj_obj = cjs({
    foo: 1
});
cobj.get('foo'); // 1
cobj.put('bar', 2);
cobj.get('bar') // 2

Creating an empty constraint

var x = cjs(),
    y = cjs(1),
    z = cjs(function() {
        return y.get() + 1;
    });
x.get(); // undefined
y.get(); // 1
z.get(); // 2

With options

var yes_lit = cjs(function() { return 1; },
                    { literal: true }),
var not_lit = cjs(function() { return 1; },
                    { literal: false });
yes_lit.get(); // (function)
not_lit.get(); // 1
cjs.array([options])

Create an array constraint

.array([options])
[options]ObjectA set of options to control how the array constraint is evaluated
Returnscjs.ArrayConstraintA new array constraint object

Example:

var arr = cjs.array({
    value: [1,2,3]
});
cjs.arrayDiff(from_val, to_val, [equality_check])

arrayDiff returns an object with attributes: removed, added, and moved. Every item in removed has the format: {item, index} Every item in added has the format: {item, index} Every item in moved has the format: {from_index, to_index} Every item in index_changed has the format: {from_index, to_index}

When oldArray removes every item in removed, adds every item in added, and moves every item in moved (in that order), it will result in an array that is equivalent to newArray. Note: this function is used internally to determine how to keep DOM nodes in sync with an underlying model with the smallest number of modifications to the DOM tree.

.arrayDiff(from_val, to_val, [equality_check])
from_valarray[*]The 'former' array
to_valarray[*]The 'new' array
[equality_check]functionA function that checks for equality between items
ReturnsObjectadded, removed, and moved items

Example:

Taking the diff between old_array and new_array with the default equality check

var old_array = ['a','b','c'],
    new_array = ['c','b','d'],
    diff = cjs.arrayDiff(old_array, new_array);

// diff === {
//   added: [ { item: 'd', to: 2, to_item: 'd' } ],
//   removed: [ { from: 0, from_item: 'a' } ],
//   moved: [ { item: 'c', from: 2, insert_at: 0, move_from: 1, to: 0 } ],
//   index_changed: [ { from: 2, from_item: 'c', item: 'c', to: 0, to_item: 'c' } ]
// }
cjs.bindAttr(...)

Constrain a DOM node's attribute values

.bindAttr(element, values)
elementdomThe DOM element
valuesobjectAn object whose key-value pairs are the attribute names and values respectively
ReturnsBindingA binding object representing the link from constraints to elements
.bindAttr(key, value)
keystringThe name of the attribute to constraint
valuecjs.Constraint,stringThe value of this attribute
ReturnsBindingA binding object representing the link from constraints to elements

Example:

If my_elem is an input element

var default_txt = cjs('enter name');
cjs.bindAttr(my_elem, 'placeholder', default_txt);

If my_elem is an input element

var default_txt = cjs('enter name'),
    name = cjs('my_name');
cjs.bindAttr(my_elem, {
    placeholder: default_txt,
    name: name
});
cjs.bindCSS(...)

Constrain a DOM node's CSS style

.bindCSS(element, values)
elementdomThe DOM element
valuesobjectAn object whose key-value pairs are the CSS property names and values respectively
ReturnsBindingA binding object representing the link from constraints to CSS styles
.bindCSS(key, value)
keystringThe name of the CSS attribute to constraint
valuecjs.Constraint,stringThe value of this CSS attribute
ReturnsBindingA binding object representing the link from constraints to elements

Example:

If my_elem is a dom element

var color = cjs('red'),
left = cjs(0);
cjs.bindCSS(my_elem, {
    "background-color": color,
    left: left.add('px')
});

If my_elem is a dom element

var color = cjs('red');
cjs.bindCSS(my_elem, ''background-color', color);
cjs.bindChildren(element, ...elements)

Constrain a DOM node's children

.bindChildren(element, ...elements)
elementdomThe DOM element
...elements*The elements to use as the constraint. The binding automatically flattens them.
ReturnsBindingA binding object

Example:

If my_elem, child1, and child2 are dom elements

var nodes = cjs(child1, child2);
cjs.bindChildren(my_elem, nodes);
cjs.bindClass(element, ...values)

Constrain a DOM node's class names

.bindClass(element, ...values)
elementdomThe DOM element
...values*The list of classes the element should have. The binding automatically flattens them.
ReturnsBindingA binding object

Example:

If my_elem is a dom element

var classes = cjs('class1 class2');
cjs.bindClass(my_elem, classes);
cjs.bindHTML(element, ...values)

Constrain a DOM node's HTML content

.bindHTML(element, ...values)
elementdomThe DOM element
...values*The desired html content
ReturnsBindingA binding object

Example:

If my_elem is a dom element

var message = cjs('<b>hello</b>');
cjs.bindHTML(my_elem, message);
cjs.bindText(element, ...values)

Constrain a DOM node's text content

.bindText(element, ...values)
elementdomThe DOM element
...values*The desired text value
ReturnsBindingA binding object

Example:

If my_elem is a dom element

var message = cjs('hello');
cjs.bindText(my_elem, message);
cjs.bindValue(element, ...values)

Constrain a DOM node's value

.bindValue(element, ...values)
elementdomThe DOM element
...values*The value the element should have
ReturnsBindingA binding object

Example:

If my_elem is a text input element

var value = cjs('hello');
cjs.bindValue(my_elem, message);
cjs.constraint(value, [options])

Constraint constructor

.constraint(value, [options])
value*The initial value of the constraint or a function to compute its value
[options]ObjectA set of options to control how and when the constraint's value is evaluated
Returnscjs.ConstraintA new constraint object
cjs.createParsedConstraint(str, context)

Parses a string and returns a constraint whose value represents the result of evaling that string

.createParsedConstraint(str, context)
strstringThe string to parse
contextobjectThe context in which to look for variables
Returnscjs.CosntraintWhether the template was successfully resumed

Example:

Creating a parsed constraint x

var a = cjs(1);
var x = cjs.createParsedConstraint("a+b", {a: a, b: cjs(2)})
x.get(); // 3
a.set(2);
x.get(); // 4
cjs.createTemplate(template, [context], [parent])

Create a new template. If context is specified, then this function returns a DOM node with the specified template. Otherwise, it returns a function that can be called with context and [parent] to create a new template.

ConstraintJS templates use a (Handlebars)[http://handlebarsjs.com/]. A template can be created with cjs.createTemplate. The format is described below.

Basics

ConstraintJS templates take standard HTML and add some features

Constraints

Unary handlebars can contain expressions.

 <h1>{{title}}</h1>
 <p>{{subtext.toUpperCase()+"!"}}</p>

called with { title: cjs('hello'), subtext: 'world'}:

<h1>hello</h1>
<p>WORLD!</p>

Literals

If the tags in a node should be treated as HTML, use triple braces: {{{ literal_val }}}. These literals (triple braces) should be created immediately under a DOM node.

 <h1>{{title}}</h1>
 <p>{{{subtext}}}</p>

called with { title: cjs('hello'), subtext: '<strong>steel</strong city'}:

<h1>hello</h1>
<p><strong>steel</strong> city</p>

Comments

{{! comments will be ignored in the output}}

Constraint output

To call my_func on event (event-name), give any targets the attribute:

data-cjs-on-(event-name)=my_func

For example:

<div data-cjs-on-click=update_obj />

Will call update_obj (a property of the template's context when this div is clicked.

To add the value of an input element to the template's context, use the property data-cjs-out:

<input data-cjs-out=user_name />
<h1>Hello, {{user_name}}</h1>

Block Helpers

Loops

To create an object for every item in an array or object, you can use the {{#each}} block helper. {{this}} refers to the current item and @key and @index refer to the keys for arrays and objects respectively.

{{#each obj_name}}
    {{@key}}: {{this}}
{{/each}}

{{#each arr_name}}
    {{@index}}: {{this}}
{{/each}}

If the length of the array is zero (or the object has no keys) then an {{#else}} block can be used:

{{#each arr_name}}
    {{@index}}: {{this}
    {{#else}}
        <strong>No items!</strong>
{{/each}}

Conditions

The {{#if}} block helper can vary the content of a template depending on some condition. This block helper can have any number of sub-conditions with the related {{#elif}} and {{#else}} tags.

{{#if cond1}}
    Cond content
{{#elif other_cond}}
    other_cond content
{{#else}}
    else content
{{/if}}

The opposite of an {{#if}} block is {{#unless}}: {{#unless logged_in}} Not logged in! {{/unless}

State

The {{#fsm}} block helper can vary the content of a template depending on an FSM state

{{#fsm my_fsm}}
    {{#state1}}
        State1 content
    {{#state2}}
        State2 content
    {{#state3}}
        State3 content
{{/fsm}}

With helper

The {{#with}} block helper changes the context in which constraints are evaluated.

{{#with obj}}
    Value: {{x}}
{{/with}}

when called with { obj: {x: 1} } results in Value: 1

Partials

Partials allow templates to be nested.

var my_temp = cjs.createTemplate(...);
cjs.registerPartial('my_template', my_temp);

Then, in any other template,

{{>my_template context}}

Nests a copy of my_template in context

.createTemplate(template, [context], [parent])
templatestring,domthe template as either a string or a script tag whose contents are the template
[context]objectAny number of target objects to listen to
[parent]domThe parent DOM node for the template
Returnsfunction,domAn event that can be attached to

Example:

<script id='my_template' type='cjs/template'>
    {{x}}
</script>
var template_elem = document.getElementById('my_template');
var template = cjs.createTemplate(template_elem);
var element1 = template({x: 1});
var element2 = template({x: 2});
var element = cjs.createTemplate("{{x}}", {x: 1});
cjs.destroyTemplate(node)

Destroy a template instance

.destroyTemplate(node)
nodedomThe dom node created by createTemplate
ReturnsbooleanWhether the template was successfully removed
cjs.fsm(...state_names)

Create an FSM

.fsm(...state_names)
...state_namesstringAn initial set of state names to add to the FSM
ReturnsFSMA new FSM

Example:

Creating a state machine with two states

var my_state = cjs.fsm("state1", "state2");
cjs.get(obj, [autoAddOutgoing=true])

Gets the value of an object regardless of if it's a constraint (standard, array, or map) or not.

.get(obj, [autoAddOutgoing=true])
obj*The object whose value to return
[autoAddOutgoing=true]booleanWhether to automatically add a dependency from this constraint to ones that depend on it.
Returns*The value

Example:

var w = 1,
    x = cjs(2),
    y = cjs(['a','b']),
    z = cjs({c: 2});

cjs.get(w); // 1
cjs.get(x); // 2
cjs.get(y); // ['a','b'] 
cjs.get(z); // {c: 2}
cjs.inFSM(fsm, values)

Create a new constraint whose value changes by state

.inFSM(fsm, values)
fsmcjs.FSMThe finite-state machine to depend on
valuesObjectKeys are the state specifications for the FSM, values are the value for those specific states
Returnscjs.ConstraintA new constraint object

Example:

var fsm = cjs.fsm("state1", "state2")
             .addTransition("state1", "state2",
                  cjs.on("click"));
var x = cjs.inFSM(fsm, {
    state1: 'val1',
    state2: function() { return 'val2'; }
});
cjs.inputValue(inp)

Take an input element and create a constraint whose value is constrained to the value of that input element

.inputValue(inp)
inpdomThe input element
Returnscjs.ConstraintA constraint whose value is the input's value

Example:

If name_input is an input element

var name = cjs.inputValue(name_input),
cjs.isArrayConstraint(obj)

Determine whether an object is an array constraint

.isArrayConstraint(obj)
obj*An object to check
Returnsbooleantrue if obj is a cjs.ArrayConstraint, false otherwise
cjs.isConstraint(obj)

Determine whether an object is a constraint

.isConstraint(obj)
obj*An object to check
Returnsbooleanobj instanceof cjs.Constraint
cjs.isFSM(obj)

Determine whether an object is an FSM

.isFSM(obj)
obj*An object to check
Returnsbooleantrue if obj is an FSM, false otherwise
cjs.isMapConstraint(obj)

Determine whether an object is a map constraint

.isMapConstraint(obj)
obj*An object to check
Returnsbooleantrue if obj is a cjs.MapConstraint, false otherwise
cjs.liven(func, [options])

Memoize a function to avoid unnecessary re-evaluation. Its options are:

  • context: The context in which func should be evaluated
  • run_on_create: Whether to run func immediately after creating the live function. (default: true)
  • pause_while_running: Whether to explicitly prevent this live function from being called recursively (default: false)
  • on_destroy: A function to call when destroy is called (default: false)

The return value of this method also has two functions:

  • pause: Pause evaluation of the live function
  • resume: Resume evaluation of the live function
  • run: Run func if it's invalid
.liven(func, [options])
funcfunctionThe function to make live
[options]objectA set of options to control how liven works
ReturnsobjectAn object with properties destroy, pause, resume, and run

Example:

var x_val = cjs(0);
var api_update = cjs.liven(function() {
    console.log('updating other x');
    other_api.setX(x_val);
}); // 'updating other x'
x_val.set(2); // 'updating other x'
cjs.map([options])

Create a map constraint

.map([options])
[options]ObjectA set of options to control how the map constraint is evaluated
Returnscjs.MapConstraintA new map constraint object

Example:

Creating a map constraint

var map_obj = cjs.map({
    value: { foo: 1 }
});
cobj.get('foo'); // 1
cobj.put('bar', 2);
cobj.get('bar') // 2
cjs.memoize(getter_fn, [options])

Memoize a function to avoid unnecessary re-evaluation. Its options are:

  • hash: Create a unique value for each set of arguments (call with an argument array)
  • equals: check if two sets of arguments are equal (call with two argument arrays)
  • context: The context in which getter_fn should be evaluated
  • literal_values: Whether values should be literal if they are functions

The return value of this method also has two functions:

  • each: Iterate through every set of arguments and value that is memoized
  • destroy: Clear the memoized values to clean up memory
.memoize(getter_fn, [options])
getter_fnfunctionThe function to memoize
[options]objectA set of options to control how memoization works
ReturnsfunctionThe memoized function

Example:

var arr = cjs([3,2,1,4,5,10]),
get_nth_largest = cjs.memoize(function(n) {
    console.log('recomputing');
    var sorted_arr = arr memoized fn.sort();
    return sorted_arr[ny];
});

get_nth_largest(0); // logfged: recomputing
get_nth_largest(0); //ulli (nothing logged because answer memoized)
arr.splice(0, 1); // N
get_nth_largest(0); // logged: recomputing
cjs.noConflict()

Restore the previous value of cjs

.noConflict()
Returnsobjectcjs

Example:

Renaming cjs to ninjaCJS

var ninjaCJS = cjs.noConflict();
var x = ninjaCJS(1);
cjs.on(event_type, ...targets=window)

Create a new event for use in a finite state machine transition

.on(event_type, ...targets=window)
event_typestringthe type of event to listen for (e.g. mousedown, timeout)
...targets=windowelement,numberAny number of target objects to listen to
ReturnsCJSEventAn event that can be attached to

Example:

When the window resizes

cjs.on("resize")

When the user clicks elem1 or elem2

cjs.on("click", elem1, elem2)

After 3 seconds

cjs.on("timeout", 3000)
cjs.pauseTemplate(node)

Pause dynamic updates to a template

.pauseTemplate(node)
nodedomThe dom node created by createTemplate
ReturnsbooleanWhether the template was successfully paused
cjs.registerCustomPartial(name, options)

Register a custom partial that can be used in other templates

Options are (only createNode is mandatory):

  • createNode(...): A function that returns a new dom node any time this partial is invoked (called with the arguments passed into the partial)
  • onAdd(dom_node): A function that is called when dom_node is added to the DOM tree
  • onRemove(dom_node): A function that is called when dom_node is removed from the DOM tree
  • pause(dom_node): A function that is called when the template has been paused (usually with pauseTemplate)
  • resume(dom_node): A function that is called when the template has been resumed (usually with resumeTemplate)
  • destroyNode(dom_node): A function that is called when the template has been destroyed (usually with destroyTemplate)
.registerCustomPartial(name, options)
namestringThe name that this partial can be referred to as
optionsObjectThe set of options (described in the description)
Returnscjscjs

Example:

Registering a custom partial named my_custom_partial

cjs.registerCustomPartial('my_custom_partial', {
        createNode: function(context) {
            return document.createElement('span');
        },
        destroyNode: function(dom_node) {
            // something like: completely_destroy(dom_node);
        }
        onAdd: function(dom_node) {
            // something like: do_init(dom_node);
        },
        onRemove: function(dom_node) {
            // something like: cleanup(dom_node);
        },
        pause: function(dom_node) {
            // something like: pause_bindings(dom_node);
        },
        resume: function(dom_node) {
            // something like: resume_bindings(dom_node);
        },
});

Then, in any other template,

{{>my_template context}}

Nests a copy of my_template in context

cjs.registerPartial(name, value)

Register a partial that can be used in other templates

.registerPartial(name, value)
namestringThe name that this partial can be referred to as
valueTemplateThe template
Returnscjscjs

Example:

Registering a partial named my_temp

var my_temp = cjs.createTemplate(...);
cjs.registerPartial('my_template', my_temp);

Then, in any other template,

{{>my_template context}}

Nests a copy of my_template in context

cjs.removeDependency(...)

Remove the edge going from fromNode to toNode

cjs.resumeTemplate(node)

Resume dynamic updates to a template

.resumeTemplate(node)
nodedomThe dom node created by createTemplate
ReturnsbooleanWhether the template was successfully resumed
cjs.signal(...)

Tells the constraint solver it is ready to run any onChange listeners. Note that signal needs to be called the same number of times as wait before the onChange listeners will run.

Example:

var x = cjs(1);
x.onChange(function() {
    console.log('x changed');
});
cjs.wait();
cjs.wait();
x.set(2);
x.set(3);
cjs.signal();
cjs.signal(); // output: x changed
cjs.toString()

Print out the name and version of ConstraintJS

.toString()
ReturnsstringConstraintJS v(version#)
cjs.unregisterPartial(name)

Unregister a partial for other templates

.unregisterPartial(name)
namestringThe name of the partial
Returnscjscjs
cjs.version

The version number of ConstraintJS

cjs.wait(...)

Tells the constraint solver to delay before running any onChange listeners

Note that signal needs to be called the same number of times as wait before the onChange listeners will run.

Example:

var x = cjs(1);
x.onChange(function() {
    console.log('x changed');
});
cjs.wait();
x.set(2);
x.set(3);
cjs.signal(); // output: x changed
new cjs.ArrayConstraint([options])

Note: The preferred constructor for arrays is cjs.array

This class is meant to emulate standard arrays, but with constraints It contains many of the standard array functions (push, pop, slice, etc) and makes them constraint-enabled.

x[1] = y[2] + z[3] === x.item(1, y.item(2) + z.item(3))

Options:

  • equals: the function to check if two values are equal, default: ===
  • value: an array for the initial value of this constraint
.ArrayConstraint([options])
[options]ObjectA set of options to control how the array constraint is evaluated
cjs.ArrayConstraint.BREAK

Any iterator in forEach can return this object to break out of its loop.

cjs.ArrayConstraint.prototype.concat(...values)

The concat() method returns a new array comprised of this array joined with other array(s) and/or value(s).

.concat(...values)
...values*Arrays and/or values to concatenate to the resulting array.
ReturnsarrayThe concatenated array

Example:

var arr1 = cjs(['a','b','c']),
arr2 = cjs(['x']);
arr1.concat(arr2); // ['a','b','c','x']
cjs.ArrayConstraint.prototype.destroy([silent=false])

Clear this array and try to clean up any memory.

.destroy([silent=false])
[silent=false]booleanIf set to true, avoids invalidating any dependent constraints.
cjs.ArrayConstraint.prototype.every(filter, thisArg)

Return true if filter against every item in my array is truthy

.every(filter, thisArg)
filterfunctionThe function to check against
thisArg*Object to use as this when executing filter.
Returnsbooleantrue if some item matches filter. false otherwise

Example:

var arr = cjs([2,4,6]);
arr.some(function(x) { return x%2===0; }); // true
cjs.ArrayConstraint.prototype.filter(callback, [thisObject])

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

.filter(callback, [thisObject])
callbackfunctionFunction to test each element of the array.
[thisObject]*Object to use as this when executing callback.
ReturnsarrayA filtered JavaScript array
cjs.ArrayConstraint.prototype.forEach(callback, thisArg)

The forEach() method executes a provided function once per array element.

.forEach(callback, thisArg)
callbackfunctionFunction to execute for each element.
thisArg*Object to use as this when executing callback.
Returnscjs.ArrayConstraintthis

Example:

var arr = cjs(['a','b','c']);
arr.forEach(function(val, i) {
    console.log(val);
    if(i === 1) {
        return cjs.ArrayConstraint.BREAK;
    }
}); // 'a' ... 'b'
cjs.ArrayConstraint.prototype.indexOf(item, [equality_check])

Returns the first index of item

.indexOf(item, [equality_check])
item*The item we are searching for
[equality_check]functionHow to check whether two objects are equal, defaults to the option that was passed in)
ReturnsnumberThe item's index or -1

Example:

var arr = cjs(['a','b','a']);
arr.indexOf('a'); // 0
cjs.ArrayConstraint.prototype.indexWhere(filter, thisArg)

Returns the first item where calling filter is truthy

.indexWhere(filter, thisArg)
filterfunctionThe function to call on every item
thisArg*Object to use as this when executing callback.
ReturnsnumberThe first index where calling filter is truthy or -1

Example:

var arr = cjs(['a','b','b']);
arr.indexWhere(function(val, i) {
    return val ==='b';
}); // 1
cjs.ArrayConstraint.prototype.item(...)

Convert my value to a standard JavaScript array

.item()
ReturnsarrayA standard JavaScript array
.item(key)
keynumberThe array index
Returns*The value at index key
.item(key, value)
keynumberThe array index
value*The new value
Returns*value

Example:

var arr = cjs([1,2,3]);
arr.item(); //[1,2,3]
var arr = cjs(['a','b']);
arr.item(0); //['a']
var arr = cjs(['a','b']);
arr.item(0,'x');
arr.toArray(); // ['x','b']
cjs.ArrayConstraint.prototype.itemConstraint(key)

Return a constraint whose value is bound to my value for key

.itemConstraint(key)
keynumber,ConstraintThe array index
ReturnsConstraintA constraint whose value is this[key]

Example:

var arr = cjs(['a','b','c']);
var first_item = arr.itemConstraint(0);
first_item.get(); // 'a'
arr.item(0,'x');
first_item.get(); // 'x'
cjs.ArrayConstraint.prototype.join([separator=','])

The join() method joins all elements of an array into a string.

.join([separator=','])
[separator=',']stringSpecifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma.
ReturnsstringThe joined string
cjs.ArrayConstraint.prototype.lastIndexOf(item, [equality_check])

Returns the last index of item

.lastIndexOf(item, [equality_check])
item*The item we are searching for
[equality_check]functionHow to check whether two objects are equal, defaults to the option that was passed in)
ReturnsnumberThe item's index or -1

Example:

var arr = cjs(['a','b','a']);
arr.indexOf('a'); // 2
cjs.ArrayConstraint.prototype.lastIndexWhere(filter, thisArg)

Returns the last item where calling filter is truthy

.lastIndexWhere(filter, thisArg)
filterfunctionThe function to call on every item
thisArg*Object to use as this when executing callback.
ReturnsnumberThe last index where calling filter is truthy or -1

Example:

var arr = cjs(['a','b','a']);
arr.lastIndexWhere(function(val, i) {
    return val ==='a';
}); // 2
cjs.ArrayConstraint.prototype.length()

Get the length of the array.

.length()
ReturnsnumberThe length of the array

Example:

var arr = cjs(['a','b']);
arr.length(); // 2
cjs.ArrayConstraint.prototype.map(callback, thisArg)

The map() method creates a new array (not array constraint) with the results of calling a provided function on every element in this array.

.map(callback, thisArg)
callbackfunctionFunction that produces an element of the new Array from an element of the current one.
thisArg*Object to use as this when executing callback.
ReturnsarrayThe result of calling callback on every element

Example:

var arr = cjs([1,2,3]);
arr.map(function(x) { return x+1;}) // [2,3,4]
cjs.ArrayConstraint.prototype.pop()

The pop() method removes the last element from an array and returns that element.

.pop()
Returns*The value that was popped off or undefined

Example:

var arr = cjs(['a','b']);
arr.pop(); // 'b'
arr.toArray(); // ['a']
cjs.ArrayConstraint.prototype.push(...elements)

The push() method mutates an array by appending the given elements and returning the new length of the array.

.push(...elements)
...elements*The set of elements to append to the end of the array
ReturnsnumberThe new length of the array

Example:

var arr = cjs(['a','b']);
arr.push('c','d'); // 4
arr.toArray(); // ['a','b','c','d']
cjs.ArrayConstraint.prototype.reverse()

The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.

.reverse()
ReturnsarrayA JavaScript array whose value is the reverse of mine
cjs.ArrayConstraint.prototype.setEqualityCheck(equality_check)

Change the equality check; useful for indexOf

.setEqualityCheck(equality_check)
equality_checkfunctionA new function to check for equality between two items in this array
Returnscjs.ArrayConstraintthis
cjs.ArrayConstraint.prototype.setValue(arr)

Replaces the whole array

.setValue(arr)
arrarrayThe new value
Returnscjs.ArrayConstraintthis

Example:

var arr = cjs([1,2,3]);
arr.toArray(); //[1,2,3]
arr.setValue(['a','b','c']);
arr.toArray(); //['a','b','c']
cjs.ArrayConstraint.prototype.shift()

The shift() method removes the first element from an array and returns that element. This method changes the length of the array.

.shift()
Returns*The element that was removed

Example:

var arr = cjs(['a','b','c']);
arr.shift(); // 'a'
arr.toArray(); //['b','c']
cjs.ArrayConstraint.prototype.slice([begin=0], [end=this.length])

The slice() method returns a portion of an array.

.slice([begin=0], [end=this.length])
[begin=0]numberZero-based index at which to begin extraction.
[end=this.length]numberZero-based index at which to end extraction. slice extracts up to but not including end.
ReturnsarrayA JavaScript array

Example:

var arr = cjs(['a','b','c']);
arr.slice(1); // ['b','c']
cjs.ArrayConstraint.prototype.some(filter, thisArg)

Return true if filter against any item in my array is truthy

.some(filter, thisArg)
filterfunctionThe function to check against
thisArg*Object to use as this when executing filter.
Returnsbooleantrue if some item matches filter. false otherwise

Example:

var arr = cjs([1,3,5]);
arr.some(function(x) { return x%2===0; }); // false
cjs.ArrayConstraint.prototype.sort([compreFunction])

The sort() method sorts the elements of an array in place and returns the array. The default sort order is lexicographic (not numeric).

.sort([compreFunction])
[compreFunction]functionSpecifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.
ReturnsarrayA sofrted JavaScript array
cjs.ArrayConstraint.prototype.splice(index, howMany, ...elements)

The splice() method changes the content of an array, adding new elements while removing old elements.

.splice(index, howMany, ...elements)
indexnumberIndex at which to start changing the array. If greater than the length of the array, no elements will be removed.
howManynumberAn integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If howMany is greater than the number of elements left in the array starting at index, then all of the elements through the end of the array will be deleted.
...elements*The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array.
Returnsarray.*An array containing the removed elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

Example:

var arr = cjs(['a','b','c']);
arr.splice(0,2,'x','y'); //['a','b']
arr.toArray(); // ['x','y','c']
cjs.ArrayConstraint.prototype.toArray()

Converts this array to a JavaScript array

.toArray()
ReturnsarrayThis object as a JavaScript array

Example:

var arr = cjs(['a','b']);
arr.toArray(); // ['a', 'b']
cjs.ArrayConstraint.prototype.toString()

The toString() method returns a string representing the specified array and its elements.

.toString()
ReturnsstringA string representation of this array.
cjs.ArrayConstraint.prototype.unshift(...elements)

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

.unshift(...elements)
...elements*The elements to be added
ReturnsnumberThe new array length

Example:

var arr = cjs(['a','b','c']);
arr.unshift('x','y'); // 5
arr.toArray(); //['x','y','a','b','c']
new cjs.Binding(options)

A binding calls some arbitrary functions passed into options. It is responsible for keeping some aspect of a DOM node in line with a constraint value. For example, it might keep an element's class name in sync with a class_name constraint

.Binding(options)
optionsobject
cjs.Binding.prototype.destroy()

Stop updating the binding and try to clean up any memory

.destroy()
Returnsundefined
cjs.Binding.prototype.pause()

Pause binding (no updates to the attribute until resume is called)

.pause()
ReturnsBindingthis
cjs.Binding.prototype.resume()

Resume binding (after pause)

.resume()
ReturnsBindingthis
cjs.Binding.prototype.throttle(min_delay)

Require at least min_delay milliseconds between setting the attribute

.throttle(min_delay)
min_delaynumberThe minimum number of milliseconds between updates
ReturnsBindingthis
new cjs.CJSEvent(...)

Note: the preferred way to create this object is with the cjs.on function Creates an event that can be used in a finite-state machine transition

cjs.CJSEvent.prototype._addTransition(transition)

Add a transition to my list of transitions that this event is attached to

._addTransition(transition)
transitionTransitionThe transition this event is attached to
cjs.CJSEvent.prototype._fire(...events)

When I fire, go through every transition I'm attached to and fire it then let any interested listeners know as well

._fire(...events)
...events*Any number of events that will be passed to the transition
cjs.CJSEvent.prototype._removeTransition(transition)

Remove a transition from my list of transitions

._removeTransition(transition)
transitionTransitionThe transition this event is attached to
cjs.CJSEvent.prototype.guard([filter])

Create a transition that calls filter whenever it fires to ensure that it should fire

.guard([filter])
[filter]functionReturns true if the event should fire and false otherwise
ReturnsCJSEventA new event that only fires when filter returns a truthy value

Example:

If the user clicks and ready is true

cjs.on("click").guard(function() {
    return ready === true;
});
new cjs.Constraint(value, [options])

Note: The preferred way to create a constraint is with the cjs.constraint function (lower-case 'c') cjs.Constraint is the constructor for the base constraint. Valid properties for options are:

  • auto_add_outgoing_dependencies: allow the constraint solver to determine when things depend on me. default: true
  • auto_add_incoming_dependencies: allow the constraint solver to determine when things I depend on things. default: true
  • cache_value: whether or not to keep track of the current value. default: true
  • check_on_nullify: when nullified, check if my value has actually changed (requires immediately re-evaluating me). default: false
  • context: if value is a function, the value of this, when that function is called. default: window
  • equals: the function to check if two values are equal, default: ===
  • literal: if value is a function, the value of the constraint should be the function itself (not its return value). default: false
  • run_on_add_listener: when onChange is called, whether or not immediately validate the value. default: true
.Constraint(value, [options])
value*The initial value of the constraint or a function to compute its value
[options]ObjectA set of options to control how and when the constraint's value is evaluated:
cjs.Constraint.prototype.abs()

Absolute value constraint modifier

.abs()
ReturnsnumberA constraint whose value is Math.abs(this.get())

Example:

x = c1.abs(); // x <- abs(c1)
cjs.Constraint.prototype.acos()

Arccosine

.acos()
ReturnsnumberA constraint whose value is Math.acos(this.get())

Example:

angle = r.div(x).acos()
cjs.Constraint.prototype.add(...args)

Addition constraint modifier

.add(...args)
...argsnumberAny number of constraints or numbers
ReturnsnumberA constraint whose value is this.get() + args[0].get() + args[1].get() + ...

Example:

x = y.add(1,2,z); // x <- y + 1 + 2 + z

The same method can also be used to add units to values

x = y.add("px"); // x <- ypx
cjs.Constraint.prototype.and(...args)

Returns the last value in the array [this].concat(args) if every value is truthy. Otherwise, returns false. Every argument won't necessarily be evaluated. For instance:

  • x = cjs(false); cjs.get(x.and(a)) does not evaluate a
.and(...args)
...args*Any number of constraints or values to pass the "and" test
Returnscjs.Constraitnboolean,*A constraint whose value is false if this or any passed in value is falsy. Otherwise, the last value passed in.

Example:

var x = c1.and(c2, c3, true);
cjs.Constraint.prototype.asin()

Arcsin

.asin()
ReturnsnumberA constraint whose value is Math.asin(this.get())

Example:

angle = r.div(y).asin()
cjs.Constraint.prototype.atan()

Arctan

.atan()
ReturnsnumberA constraint whose value is Math.atan(this.get())

Example:

angle = y.div(x).atan()
cjs.Constraint.prototype.atan2(x)

Arctan2

.atan2(x)
xnumber,cjs.Constraint
ReturnsnumberA constraint whose value is Math.atan2(this.get()/x.get())

Example:

angle = y.atan2(x)
cjs.Constraint.prototype.bitwiseNot()

Bitwise not operator

.bitwiseNot()
ReturnsnumberA constraint whose value is ~(this.get())

Example:

inverseBits = val.bitwiseNot()
cjs.Constraint.prototype.ceil()

Ceil

.ceil()
ReturnsnumberA constraint whose value is Math.ceil(this.get())

Example:

x = c1.ceil(); // x <- ceil(c1)
cjs.Constraint.prototype.cos()

Cosine

.cos()
ReturnsnumberA constraint whose value is Math.cos(this.get())

Example:

dx = r.mul(angle.cos())
cjs.Constraint.prototype.destroy([silent=false])

Removes any dependent constraint, clears this constraints options, and removes every change listener. This is useful for making sure no memory is deallocated

.destroy([silent=false])
[silent=false]booleanIf set to true, avoids invalidating any dependent constraints.
Returnscjs.Constraintthis

Example:

var x = cjs(1);
x.destroy(); // ...x is no longer needed
cjs.Constraint.prototype.div(...args)

Division constraint modifier

.div(...args)
...argsnumberAny number of constraints or numbers
ReturnsnumberA constraint whose value is this.get() / args[0].get() / args[1].get() / ...

Example:

x = y.div(1,2,z); // x <- y / 1 / 2 / z
cjs.Constraint.prototype.eq(other)

Equals unary operator

.eq(other)
other*A constraint or value to compare against
ReturnsbooleanA constraint whose value is this.get() == other.get()

Example:

isNull = val.eq(null)
cjs.Constraint.prototype.eqStrict(other)

Strict equals operator

.eqStrict(other)
other*A constraint or value to compare against
ReturnsbooleanA constraint whose value is this.get() === other.get()

Example:

isOne = val.eqStrict(1)
cjs.Constraint.prototype.exp()

Exp (E^x)

.exp()
ReturnsnumberA constraint whose value is Math.exp(this.get())

Example:

neg_1 = cjs(i*pi).exp()
cjs.Constraint.prototype.floor()

Floor

.floor()
ReturnsnumberA constraint whose value is Math.floor(this.get())

Example:

x = c1.floor(); // x <- floor(c1)
cjs.Constraint.prototype.get([autoAddOutgoing=true])

Get the current value of this constraint. For computed constraints, if the constraint is invalid, its value will be re-computed.

.get([autoAddOutgoing=true])
[autoAddOutgoing=true]booleanWhether to automatically add a dependency from this constraint to ones that depend on it.
Returns*The current constraint value

Example:

var x = cjs(1);
x.get(); // 1
cjs.Constraint.prototype.iif(true_val, other_val)

Inline if function: similar to the javascript a ? b : c expression

.iif(true_val, other_val)
true_val*The value to return if this is truthy
other_val*The value to return if this is falsy
Returnscjs.ConstraintA constraint whose value is false if this or any passed in value is falsy. Otherwise, the last value passed in.

Example:

var x = is_selected.iif(selected_val, nonselected_val);
cjs.Constraint.prototype.inFSM(fsm, values)

Change this constraint's value in different states

.inFSM(fsm, values)
fsmcjs.FSMThe finite-state machine to depend on
valuesObjectKeys are the state specifications for the FSM, values are the value for those specific states
Returnscjs.Constraintthis

Example:

var fsm = cjs.fsm("state1", "state2")
             .addTransition("state1", "state2",
                   cjs.on("click"));
var x = cjs().inFSM(fsm, {
    state1: 'val1',
    state2: function() { return 'val2'; }
});
cjs.Constraint.prototype.instanceOf(other)

Object instance check modifier

.instanceOf(other)
other*a constraint or value to compare against
Returnsbooleana constraint whose value is this.get() instanceof other.get()

Example:

var valIsArray = val.instanceof(Array)
cjs.Constraint.prototype.invalidate()

Mark this constraint's value as invalid. This signals that the next time its value is fetched, it should be recomputed, rather than returning the cached value.

An invalid constraint's value is only updated when it is next requested (for example, via .get()).

.invalidate()
Returnscjs.Constraintthis

Example:

Tracking the window height var height = cjs(window.innerHeight); window.addEventListener("resize", function() { height.invalidate(); });

cjs.Constraint.prototype.isValid()

Find out if this constraint's value needs to be recomputed (i.e. whether it's invalid).

An invalid constraint's value is only updated when it is next requested (for example, via .get()).

.isValid()
Returnsbooleantrue if this constraint's current value is valid. false otherwise.

Example:

var x = cjs(1),
    y = x.add(2);
y.get();     // 3
y.isValid(); // true
x.set(2);
y.isValid(); // false
y.get();     // 4
y.isValid(); //true
cjs.Constraint.prototype.log()

Natural Log (base e)

.log()
ReturnsnumberA constraint whose value is Math.log(this.get())

Example:

num_digits = num.max(2).log().div(Math.log(10)).ceil()
cjs.Constraint.prototype.max(...args)

Max

.max(...args)
...argsnumberAny number of constraints or numbers
ReturnsnumberA constraint whose value is the highest of this.get(), args[0].get(), args[1].get()...

Example:

val = val1.max(val2, val3);
cjs.Constraint.prototype.min(...args)

Min

.min(...args)
...argsnumberAny number of constraints or numbers
ReturnsnumberA constraint whose value is the lowest of this.get(), args[0].get(), args[1].get()...

Example:

val = val1.min(val2, val3);
cjs.Constraint.prototype.mul(...args)

Multiplication constraint modifier

.mul(...args)
...argsnumberAny number of constraints or numbers
ReturnsnumberA constraint whose value is this.get() * args[0].get() * args[1].get() * ...

Example:

x = y.mul(1,2,z); //x <- y * 1 * 2 * z
cjs.Constraint.prototype.neg()

Negative operator

.neg()
ReturnsnumberA constraint whose value is -(this.get())

Example:

neg_val = x.neg()
cjs.Constraint.prototype.neq(other)

Not equals operator

.neq(other)
other*A constraint or value to compare against
ReturnsbooleanA constraint whose value is this.get() != other.get()

Example:

notNull = val.neq(null)
cjs.Constraint.prototype.neqStrict(other)

Not strict equals binary operator

.neqStrict(other)
other*A constraint or value to compare against
ReturnsbooleanA constraint whose value is this.get() !== other.get()

Example:

notOne = val.neqStrict(1)
cjs.Constraint.prototype.not()

Not operator

.not()
ReturnsbooleanA constraint whose value is !(this.get())

Example:

opposite = x.not()
cjs.Constraint.prototype.offChange(callback, [thisArg])

Removes the first listener to callback that was created by onChange. thisArg is optional and if specified, it only removes listeners within the same context. If thisArg is not specified, the first callback is removed.

.offChange(callback, [thisArg])
callbackfunction
[thisArg]*If specified, only remove listeners that were added with this context
Returnscjs.Constraintthis
cjs.Constraint.prototype.onChange(callback, [thisArg=window], ...args)

Call callback as soon as this constraint's value is invalidated. Note that if the constraint's value is invalidated multiple times, callback is only called once.

.onChange(callback, [thisArg=window], ...args)
callbackfunction
[thisArg=window]*The context to use for callback
...args*The first args.length arguments to callback
Returnscjs.Constraintthis

Example:

var x = cjs(1);
x.onChange(function() {
    console.log("x is " + x.get());
});
x.set(2); // x is 2
cjs.Constraint.prototype.or(...args)

Returns the first truthy value in the array [this].concat(args). If no value is truthy, returns false. Every argument won't necessarily be evaluated. For instance:

  • y = cjs(true); cjs.get(y.or(b)) does not evaluate b
.or(...args)
...args*Any number of constraints or values to pass the "or" test
Returnscjs.ConstraintA constraitn whose value is the first truthy value or false if there aren't any

Example:

var x = c1.or(c2, c3, false);
cjs.Constraint.prototype.pauseGetter(temporaryValue)

Signal that this constraint's value will be computed later. For instance, for asyncronous values.

.pauseGetter(temporaryValue)
temporaryValue*The temporary value to use for this node until it is resumed
Returnscjs.Constraintthis
cjs.Constraint.prototype.pos()

Coerce an object to a number

.pos()
ReturnsnumberA constraint whose value is +(this.get())

Example:

numeric_val = val.pos()
cjs.Constraint.prototype.pow(x)

Power

.pow(x)
xnumberThe exponent
ReturnsnumberA constraint whose value is Math.pow(this.get(), x.get())

Example:

d = dx.pow(2).add(dy.pow(2)).sqrt()
cjs.Constraint.prototype.prop(...args)

Property constraint modifier.

.prop(...args)
...argsstringsAny number of properties to fetch
Returns*A constraint whose value is this[args[0]][args[1]]...

Example:

w = x.prop("y", "z"); // means w <- x.y.z
cjs.Constraint.prototype.remove([silent=false])

Removes every dependency to this node

.remove([silent=false])
[silent=false]booleanIf set to true, avoids invalidating any dependent constraints.
Returnscjs.Constraintthis
cjs.Constraint.prototype.resumeGetter(value)

Signal that this Constraint, which has been paused with pauseGetter now has a value.

.resumeGetter(value)
value*This node's value
Returnscjs.Constraintthis
cjs.Constraint.prototype.round()

Round

.round()
ReturnsnumberA constraint whose value is Math.round(this.get())

Example:

x = c1.round(); // x <- round(c1)
cjs.Constraint.prototype.set(value, [options])

Change the current value of the constraint. Other constraints that depend on its value will be invalidated.

.set(value, [options])
value*The initial value of the constraint or a function to compute its value
[options]ObjectA set of options to control how and when the constraint's value is evaluated:
Returnscjs.Constraintthis

Example:

var x = cjs(1); x.get(); // 1 x.set(function() { return 2; }); x.get(); // 2 x.set('c'); x.get(); // 'c'

cjs.Constraint.prototype.setOption(options)

Change how this constraint is computed (see Constraint options)

.setOption(options)
optionsObjectAn object with the options to change
Returnscjs.Constraintthis

Example:

var x = cjs(function() { return 1; });
x.get(); // 1
x.setOption({
    literal: true,
    auto_add_outgoing_dependencies: false
});
x.get(); // (function)
cjs.Constraint.prototype.sin()

Sine

.sin()
ReturnsnumberA constraint whose value is Math.sin(this.get())

Example:

dy = r.mul(angle.sin())
cjs.Constraint.prototype.sqrt()

Square root

.sqrt()
ReturnsnumberA constraint whose value is Math.sqrt(this.get())

Example:

x = c1.sqrt(); // x <- sqrt(c1)
cjs.Constraint.prototype.sub(...args)

Subtraction constraint modifier

.sub(...args)
...argsnumberAny number of constraints or numbers
ReturnsnumberA constraint whose value is this.get() - args[0].get() - args[1].get() - ...

Example:

x = y.sub(1,2,z); // x <- y - 1 - 2 - z
cjs.Constraint.prototype.tan()

Tangent

.tan()
ReturnsnumberA constraint whose value is Math.tan(this.get())

Example:

dy = r.mul(angle.sin())
cjs.Constraint.prototype.toFloat()

Float conversion constraint modifier.

.toFloat()
Returns*A constraint whose value is parseFloat(this)

Example:

Given <input /> element inp_elem

var inp_val = cjs(inp_elem).toFloat();
cjs.Constraint.prototype.toInt()

Integer conversion constraint modifier.

.toInt()
Returns*A constrant whose value is parseInt(this)

Example:

Given <input /> element inp_elem

var inp_val = cjs(inp_elem).toInt();
cjs.Constraint.prototype.typeOf(other)

Object type modifier

.typeOf(other)
other*a constraint or value to compare against
Returns*a constraint whose value is typeof this.get()

Example:

var valIsNumber = val.typeOf().eq('[object Number]')
new cjs.FSM(...state_names)

Note: The preferred way to create a FSM is through the cjs.fsm function This class represents a finite-state machine to track the state of an interface or component

.FSM(...state_names)
...state_namesstringAny number of state names for the FSM to have
cjs.FSM.state

The name of this FSM's active state

Example:

var my_fsm = cjs.fsm("state1", "state2");
my_fsm.state.get(); // 'state1'
cjs.FSM.prototype._setState(state, transition)

Changes the active state of this FSM. This function should, ideally, be called by a transition instead of directly.

._setState(state, transition)
stateState,stringThe state to transition to
transitionTransitionThe transition that ran
cjs.FSM.prototype.addState(...state_names)

Create states and set the current "chain state" to that state

.addState(...state_names)
...state_namesstringAny number of state names to add. The last state becomes the chain state
ReturnsFSMthis

Example:

var fsm = cjs.fsm()
             .addState('state1')
             .addState('state2')
             .addTransition('state2', cjs.on('click'));
cjs.FSM.prototype.addTransition(...)

Add a transition between two states

.addTransition(to_state)
to_statestringThe name of the state the transition should go to
ReturnsfunctionA function that tells the transition to run
.addTransition(to_state, add_transition_fn)
to_statestringThe name of the state the transition should go to
add_transition_fnCJSEvent,functionA CJSEvent or a user-specified function for adding the event listener
ReturnsFSMthis
.addTransition(from_state, to_state)
from_statestringThe name of the state the transition should come from
to_statestringThe name of the state the transition should go to
ReturnsfunctionA function that tells the transition to run
.addTransition(from_state, to_state, add_transition_fn)
from_statestringThe name of the state the transition should come from
to_statestringThe name of the state the transition should go to
add_transition_fnCJSEvent,functionA CJSEvent or a user-specified function for adding the event listener
ReturnsFSMthis

Example:

var x = cjs.fsm();
x.addState("b")
 .addState("a");
var run_transition = x.addTransition("b");
//add a transition from a to b
window.addEventListener("click", run_transition);
// run that transition when the window is clicked
var x = cjs.fsm();
x.addState("b")
 .addState("a")
 .addTransition("b", cjs.on('click'));
// add a transition from a to b that runs when the window is clicked
var x = cjs.fsm();
x.addState("b")
 .addState("a")
 .addTransition("b", function(run_transition) {
     window.addEventListener("click", run_transition);
 });
// add a transition from a to b that runs when the window is clicked
var x = cjs.fsm("a", "b");
var run_transition = x.addTransition("a", "b"); //add a transition from a to b
window.addEventListener("click", run_transition); // run that transition when the window is clicked
var x = cjs.fsm("a", "b");
x.addTransition("a", "b", cjs.on("click"));
var x = cjs.fsm("a", "b");
var run_transition = x.addTransition("a", "b", function(run_transition) {
    window.addEventListener("click", run_transition);
}); // add a transition from a to b that runs when the window is clicked
cjs.FSM.prototype.destroy(...)

Remove all of the states and transitions of this FSM. Useful for cleaning up memory

cjs.FSM.prototype.getState()

Returns the name of the state this machine is currently in. Constraints that depend on the return value will be automatically updated.

.getState()
ReturnsstringThe name of the currently active state

Example:

var my_fsm = cjs.fsm("state1", "state2");
my_fsm.getState(); // 'state1'
cjs.FSM.prototype.is(state_name)

Check if the current state is state_name

.is(state_name)
state_namestringThe name of the state to check against
Returnsbooleantrue if the name of the active state is state_name. false otherwise

Example:

var my_fsm = cjs.fsm("a", "b");
my_fsm.is("a"); // true, because a is the starting state
cjs.FSM.prototype.off(callback)

Remove the listener specified by an on call; pass in just the callback

.off(callback)
callbackfunctionThe function to remove as a callback
ReturnsFSMthis
cjs.FSM.prototype.on(spec, callback, [context])

Call a given function when the finite-state machine enters a given state. spec can be of the form:

  • '*': any state
  • 'state1': A state named state1
  • 'state1 -> state2': Immediately after state1 transitions to state2
  • 'state1 >- state2': Immediately before state1 transitions to state2
  • 'state1 <-> state2': Immediately after any transition between state1 and state2
  • 'state1 >-< state2': Immediately before any transition between state1 and state2
  • 'state1 <- state2': Immediately after state2 transitions 2 state1
  • 'state1 -< state2': Immediately before state2 transitions 2 state1
  • 'state1 -> *': Any transition from state1
  • '* -> state2': Any transition to state2
.on(spec, callback, [context])
specstringA specification of which state to call the callback
callbackfunctionThe function to be called
[context]objectWhat this should evaluate to when callback is called
ReturnsFSMthis

Example:

var x = cjs.fsm("a", "b");
x.on("a->b", function() {...});
cjs.FSM.prototype.startsAt(state_name)

Specify which state this FSM should begin at.

.startsAt(state_name)
state_namestringThe name of the state to start at
ReturnsFSMthis

Example:

var my_fsm = cjs.fsm("state_a", "state_b");
my_fsm.startsAt("state_b");
new cjs.MapConstraint([options])

Note: the preferred way to create a map constraint is with cjs.map This class is meant to emulate JavaScript objects ({}) but with constraints

Options:

  • hash: a key hash to use to improve performance when searching for a key (default: x.toString())
  • valuehash: a value hash to use improve performance when searching for a value (default: false)
  • equals: How to check for equality when searching for a key (default: ===)
  • valueequals: How to check for equality when searching for a value (default: ===)
  • value: An optional starting value (default: {})
  • keys: An optional starting set of keys (default: [])
  • values: An optional starting set of values (default: [])
  • literal_values: True if values that are functions should return a function rather than that function's return value. (default: false)
  • create_unsubstantiated: Create a constraint when searching for non-existent keys. (default: true)
.MapConstraint([options])
[options]ObjectA set of options to control how the map constraint is evaluated
cjs.MapConstraint.BREAK

Any iterator in forEach can return this object to break out of its loop.

cjs.MapConstraint.prototype.clear()

Clear every entry of this object.

.clear()
Returnscjs.MapConstraintthis

Example:

var map = cjs({x: 1, y: 2});
map.isEmpty(); // false
map.clear();
map.isEmpty(); // true
cjs.MapConstraint.prototype.destroy([silent=false])

Clear this object and try to clean up any memory.

.destroy([silent=false])
[silent=false]booleanIf set to true, avoids invalidating any dependent constraints.
cjs.MapConstraint.prototype.entries()

Get every key and value of this object as an array.

.entries()
Returnsarray.objectA set of objects with properties key and value

Example:

var map = cjs({x: 1, y: 2});
map.entries(); // [{key:'x',value:1},
               //  {key:'y',value:2}]
cjs.MapConstraint.prototype.forEach(callback, thisArg)

The forEach() method executes a provided function once per entry. If cjs.MapConstraint.BREAK is returned for any element, we stop looping

.forEach(callback, thisArg)
callbackfunctionFunction to execute for each entry.
thisArg*Object to use as this when executing callback.
Returnscjs.MapConstraintthis

Example:

var map = cjs({x:1,y:2,z:3});
map.forEach(function(val, key) {
    console.log(key+':'+val);
    if(key === 'y') {
        return cjs.MapConstraint.BREAK;
    }
}); // x:1 ... y:2
cjs.MapConstraint.prototype.get(key)

Get the item at key (like this[key])

.get(key)
key*The entry's key
Returns*,undefinedthe value at that entry or undefined

Example:

var map = cjs({x: 1, y: 2});
map.get("x"); // 1
cjs.MapConstraint.prototype.getOrPut(key, create_fn, [create_fn_context], [index=this.size], [literal=false])

Search for a key or create it if it wasn't found

.getOrPut(key, create_fn, [create_fn_context], [index=this.size], [literal=false])
key*The key to search for.
create_fnfunctionA function to create the value if key is not found
[create_fn_context]*The context in which to call create_fn
[index=this.size]numberWhere to place a value that is created
[literal=false]booleanWhether to create the value as a literal constraint (the value of a function is the function)
ReturnsnumberThe index of the entry with key=key or -1

Example:

var map = xjs({x: 1, y: 2});
map.getOrPut('x', function() {
    console.log("evaluating");
    return 3;
}); // output: 'evaluating'
// 3
map.getOrPut('x', function() {
    console.log("evaluating");
    return 3;
}); // (no output)
// 3
cjs.MapConstraint.prototype.has(key)

Check if there is any entry with key = key

.has(key)
key*The key to search for.
Returnsbooleantrue if there is an entry with key=key, false otherwise.

Example:

var map = cjs({x: 1, y: 2});
map.has('x'); // true
cjs.MapConstraint.prototype.indexOf(key)

Get the index of the entry with key = key

.indexOf(key)
key*The key to search for.
ReturnsnumberThe index of the entry with key=key or -1

Example:

var map = cjs({x: 1, y: 2});
map.indexOf('z'); // -1
cjs.MapConstraint.prototype.isEmpty()

Check if this object has any entries

.isEmpty()
Returnsbooleantrue if there are no entries, false otherwise

Example:

var map = cjs({x: 1, y: 2});
map.isEmpty(); // false
cjs.MapConstraint.prototype.item(...)

Convert my value to a standard JavaScript object. The keys are converted using toString

.item()
ReturnsobjectA standard JavaScript object
.item(key)
keynumberThe object key
Returns*The value at index key
.item(key, value)
keynumberThe object key
value*The new value
Returnscjs.MapConstraintthis

Example:

var map = cjs({x: 1, y: 2});
map.item(); // {x:1,y:2}
var map = cjs({x: 1, y: 2});
map.item('x'); // 1
var map = cjs({x: 1, y: 2});
map.item('z', 3);
map.keys(); //['x','y','z']
cjs.MapConstraint.prototype.itemConstraint(key)

Return a constraint whose value is bound to my value for key

.itemConstraint(key)
key*,ConstraintThe array index
ReturnsConstraintA constraint whose value is this[key]

Example:

var map = cjs({x: 1, y: 2});
var x_val = map.itemConstraint('x');
x_val.get(); // 1
map.item('x', 3);
x_val.get(); // 3
cjs.MapConstraint.prototype.keyForValue(value, [eq_check])

Given a value, find the corresponding key

.keyForValue(value, [eq_check])
value*The value whose key to search for
[eq_check]functionHow to check if two values are equal (default: ===
Returns*,undefinedThe key where this.get(key)===value

Example:

var map = cjs({x: 1, y: 2, z: 3});
map.keyForValue(1); // 'x'
cjs.MapConstraint.prototype.keys()

Get the keys on this object.

.keys()
Returnsarray.*The set of keys

Example:

var map = cjs({x: 1, y: 2});
map.keys(); // ['x','y']
cjs.MapConstraint.prototype.move(key, to_index)

Move the entry with key key to `index

.move(key, to_index)
key*The key to search for
to_indexnumberThe new index for the key
Returnscjs.ArrayConstraintthis

Example:

var map = cjs({x: 1, y: 2, z: 3});
map.keys(); // ['x','y', 'z']
map.move('z', 0)
map.keys(); // ['z','x', 'y']
cjs.MapConstraint.prototype.moveIndex(old_index, new_index)

Move the entry at old_index to index new_index

.moveIndex(old_index, new_index)
old_indexnumberThe index to move from
new_indexnumberThe index to move to
Returnscjs.ArrayConstraintthis

Example:

var map = cjs({x: 1, y: 2, z: 3});
map.keys(); // ['x','y', 'z']
map.moveIndex(1, 0)
map.keys(); // ['y','x', 'z']
cjs.MapConstraint.prototype.put(key, value, [index=this.size], [literal])

Set the entry for key to value (this[key]=value)

.put(key, value, [index=this.size], [literal])
key*The entry's key
value*The entry's value
[index=this.size]numberThe entry's index
[literal]booleanWhether to treat the value as literal
Returnscjs.MapConstraintthis

Example:

var map = cjs({x: 1, y: 2});
map.put("z", 3, 1);
map.keys(); // ['x','z','y']
cjs.MapConstraint.prototype.remove(key)

Remove a key's entry (like delete this[key])

.remove(key)
key*The entry's key
Returnscjs.MapConstraintthis

Example:

var map = cjs({x: 1, y: 2});
map.remove("x");
map.keys(); // ['y']
cjs.MapConstraint.prototype.setEqualityCheck(equality_check)

Change the default equality check when getting a key

.setEqualityCheck(equality_check)
equality_checkfunctionThe new key equality check
Returnscjs.ArrayConstraintthis
cjs.MapConstraint.prototype.setHash(hash)

Change the hash function when getting a key

.setHash(hash)
hashfunction,stringThe new hashing function (or a string representing a property name for every key to use as the hash)
Returnscjs.ArrayConstraintthis
cjs.MapConstraint.prototype.setValueEqualityCheck(vequality_check)

Change the default value equality check when getting a value

.setValueEqualityCheck(vequality_check)
vequality_checkfunctionThe new value equality check
Returnscjs.ArrayConstraintthis
cjs.MapConstraint.prototype.setValueHash(hash)

Change the hash function when getting a value

.setValueHash(hash)
hashfunction,stringThe new hashing function (or a string representing a property name for every key to use as the hash)
Returnscjs.ArrayConstraintthis
cjs.MapConstraint.prototype.size()

Get the number of entries in this object.

.size()
ReturnsnumberThe number of entries

Example:

var map = cjs({x: 1, y: 2});
map.size(); // 2
cjs.MapConstraint.prototype.toObject([key_map_fn])

Converts this array to a JavaScript object.

.toObject([key_map_fn])
[key_map_fn]functionA function to convert keys
ReturnsobjectThis object as a JavaScript object

Example:

var map = cjs({x: 1, y: 2, z: 3});
map.toObject(); // {x:1,y:2,z:3}
cjs.MapConstraint.prototype.values()

Get the values on this object.

.values()
Returnsarray.*The set of values

Example:

var map = cjs({x: 1, y: 2});
map.values(); // [1,2]