ConstraintJS API
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) | ||
value | object | A map of initial values |
options | object | A set of options to control how the array constraint is evaluated |
Returns | cjs.ArrayConstraint | A new array constraint |
cjs(node) | ||
node | dom | The DOM node whose value to follow |
Returns | cjs.Binding | A constraint whose value is the current value of the input |
cjs(value, options) | ||
value | object | A map of initial values |
options | object | A set of options to control how the map constraint is evaluated |
Returns | cjs.MapConstraint | A new map constraint |
cjs(value, options) | ||
value | object | The constraint's value |
options | object | A set of options to control how the constraint is evaluated |
Returns | cjs.Constraint | A 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
Create an array constraint
.array([options]) | ||
[options] | Object | A set of options to control how the array constraint is evaluated |
Returns | cjs.ArrayConstraint | A new array constraint object |
Example:
var arr = cjs.array({
value: [1,2,3]
});
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_val | array[*] | The 'former' array |
to_val | array[*] | The 'new' array |
[equality_check] | function | A function that checks for equality between items |
Returns | Object | added, 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' } ]
// }
Constrain a DOM node's attribute values
.bindAttr(element, values) | ||
element | dom | The DOM element |
values | object | An object whose key-value pairs are the attribute names and values respectively |
Returns | Binding | A binding object representing the link from constraints to elements |
.bindAttr(key, value) | ||
key | string | The name of the attribute to constraint |
value | cjs.Constraint,string | The value of this attribute |
Returns | Binding | A 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
});
Constrain a DOM node's CSS style
.bindCSS(element, values) | ||
element | dom | The DOM element |
values | object | An object whose key-value pairs are the CSS property names and values respectively |
Returns | Binding | A binding object representing the link from constraints to CSS styles |
.bindCSS(key, value) | ||
key | string | The name of the CSS attribute to constraint |
value | cjs.Constraint,string | The value of this CSS attribute |
Returns | Binding | A 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);
Constrain a DOM node's children
.bindChildren(element, ...elements) | ||
element | dom | The DOM element |
...elements | * | The elements to use as the constraint. The binding automatically flattens them. |
Returns | Binding | A binding object |
Example:
If my_elem
, child1
, and child2
are dom elements
var nodes = cjs(child1, child2);
cjs.bindChildren(my_elem, nodes);
Constrain a DOM node's class names
.bindClass(element, ...values) | ||
element | dom | The DOM element |
...values | * | The list of classes the element should have. The binding automatically flattens them. |
Returns | Binding | A binding object |
Example:
If my_elem
is a dom element
var classes = cjs('class1 class2');
cjs.bindClass(my_elem, classes);
Constrain a DOM node's HTML content
.bindHTML(element, ...values) | ||
element | dom | The DOM element |
...values | * | The desired html content |
Returns | Binding | A binding object |
Example:
If my_elem
is a dom element
var message = cjs('<b>hello</b>');
cjs.bindHTML(my_elem, message);
Constrain a DOM node's text content
.bindText(element, ...values) | ||
element | dom | The DOM element |
...values | * | The desired text value |
Returns | Binding | A binding object |
Example:
If my_elem
is a dom element
var message = cjs('hello');
cjs.bindText(my_elem, message);
Constrain a DOM node's value
.bindValue(element, ...values) | ||
element | dom | The DOM element |
...values | * | The value the element should have |
Returns | Binding | A binding object |
Example:
If my_elem
is a text input element
var value = cjs('hello');
cjs.bindValue(my_elem, message);
Constraint constructor
.constraint(value, [options]) | ||
value | * | The initial value of the constraint or a function to compute its value |
[options] | Object | A set of options to control how and when the constraint's value is evaluated |
Returns | cjs.Constraint | A new constraint object |
Parses a string and returns a constraint whose value represents the result of eval
ing
that string
.createParsedConstraint(str, context) | ||
str | string | The string to parse |
context | object | The context in which to look for variables |
Returns | cjs.Cosntraint | Whether 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
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]) | ||
template | string,dom | the template as either a string or a script tag whose contents are the template |
[context] | object | Any number of target objects to listen to |
[parent] | dom | The parent DOM node for the template |
Returns | function,dom | An 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});
Destroy a template instance
.destroyTemplate(node) | ||
node | dom | The dom node created by createTemplate |
Returns | boolean | Whether the template was successfully removed |
Create an FSM
.fsm(...state_names) | ||
...state_names | string | An initial set of state names to add to the FSM |
Returns | FSM | A new FSM |
Example:
Creating a state machine with two states
var my_state = cjs.fsm("state1", "state2");
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] | boolean | Whether 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}
Create a new constraint whose value changes by state
.inFSM(fsm, values) | ||
fsm | cjs.FSM | The finite-state machine to depend on |
values | Object | Keys are the state specifications for the FSM, values are the value for those specific states |
Returns | cjs.Constraint | A 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'; }
});
Take an input element and create a constraint whose value is constrained to the value of that input element
.inputValue(inp) | ||
inp | dom | The input element |
Returns | cjs.Constraint | A constraint whose value is the input's value |
Example:
If name_input
is an input element
var name = cjs.inputValue(name_input),
Determine whether an object is an array constraint
.isArrayConstraint(obj) | ||
obj | * | An object to check |
Returns | boolean | true if obj is a cjs.ArrayConstraint , false otherwise |
Determine whether an object is a constraint
.isConstraint(obj) | ||
obj | * | An object to check |
Returns | boolean | obj instanceof cjs.Constraint |
Determine whether an object is an FSM
.isFSM(obj) | ||
obj | * | An object to check |
Returns | boolean | true if obj is an FSM , false otherwise |
Determine whether an object is a map constraint
.isMapConstraint(obj) | ||
obj | * | An object to check |
Returns | boolean | true if obj is a cjs.MapConstraint , false otherwise |
Memoize a function to avoid unnecessary re-evaluation. Its options are:
context
: The context in whichfunc
should be evaluatedrun_on_create
: Whether to runfunc
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 whendestroy
is called (default:false
)
The return value of this method also has two functions:
pause
: Pause evaluation of the live functionresume
: Resume evaluation of the live functionrun
: Runfunc
if it's invalid
.liven(func, [options]) | ||
func | function | The function to make live |
[options] | object | A set of options to control how liven works |
Returns | object | An 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'
Create a map constraint
.map([options]) | ||
[options] | Object | A set of options to control how the map constraint is evaluated |
Returns | cjs.MapConstraint | A 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
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 whichgetter_fn
should be evaluatedliteral_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 memoizeddestroy
: Clear the memoized values to clean up memory
.memoize(getter_fn, [options]) | ||
getter_fn | function | The function to memoize |
[options] | object | A set of options to control how memoization works |
Returns | function | The 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
Restore the previous value of cjs
.noConflict() | ||
Returns | object | cjs |
Example:
Renaming cjs
to ninjaCJS
var ninjaCJS = cjs.noConflict();
var x = ninjaCJS(1);
Create a new event for use in a finite state machine transition
.on(event_type, ...targets=window) | ||
event_type | string | the type of event to listen for (e.g. mousedown, timeout) |
...targets=window | element,number | Any number of target objects to listen to |
Returns | CJSEvent | An 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)
Pause dynamic updates to a template
.pauseTemplate(node) | ||
node | dom | The dom node created by createTemplate |
Returns | boolean | Whether the template was successfully paused |
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 whendom_node
is added to the DOM treeonRemove(dom_node)
: A function that is called whendom_node
is removed from the DOM treepause(dom_node)
: A function that is called when the template has been paused (usually withpauseTemplate
)resume(dom_node)
: A function that is called when the template has been resumed (usually withresumeTemplate
)destroyNode(dom_node)
: A function that is called when the template has been destroyed (usually withdestroyTemplate
)
.registerCustomPartial(name, options) | ||
name | string | The name that this partial can be referred to as |
options | Object | The set of options (described in the description) |
Returns | cjs | cjs |
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
Register a partial that can be used in other templates
.registerPartial(name, value) | ||
name | string | The name that this partial can be referred to as |
value | Template | The template |
Returns | cjs | cjs |
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
Remove the edge going from fromNode
to toNode
Resume dynamic updates to a template
.resumeTemplate(node) | ||
node | dom | The dom node created by createTemplate |
Returns | boolean | Whether the template was successfully resumed |
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
Print out the name and version of ConstraintJS
.toString() | ||
Returns | string | ConstraintJS v(version#) |
Unregister a partial for other templates
.unregisterPartial(name) | ||
name | string | The name of the partial |
Returns | cjs | cjs |
The version number of ConstraintJS
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
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] | Object | A set of options to control how the array constraint is evaluated |
Any iterator in forEach can return this object to break out of its loop.
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. |
Returns | array | The concatenated array |
Example:
var arr1 = cjs(['a','b','c']),
arr2 = cjs(['x']);
arr1.concat(arr2); // ['a','b','c','x']
Clear this array and try to clean up any memory.
.destroy([silent=false]) | ||
[silent=false] | boolean | If set to true , avoids invalidating any dependent constraints. |
Return true
if filter
against every item in my array is truthy
.every(filter, thisArg) | ||
filter | function | The function to check against |
thisArg | * | Object to use as this when executing filter . |
Returns | boolean | true if some item matches filter . false otherwise |
Example:
var arr = cjs([2,4,6]);
arr.some(function(x) { return x%2===0; }); // true
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
.filter(callback, [thisObject]) | ||
callback | function | Function to test each element of the array. |
[thisObject] | * | Object to use as this when executing callback. |
Returns | array | A filtered JavaScript array |
The forEach() method executes a provided function once per array element.
.forEach(callback, thisArg) | ||
callback | function | Function to execute for each element. |
thisArg | * | Object to use as this when executing callback . |
Returns | cjs.ArrayConstraint | this |
Example:
var arr = cjs(['a','b','c']);
arr.forEach(function(val, i) {
console.log(val);
if(i === 1) {
return cjs.ArrayConstraint.BREAK;
}
}); // 'a' ... 'b'
Returns the first index of item
.indexOf(item, [equality_check]) | ||
item | * | The item we are searching for |
[equality_check] | function | How to check whether two objects are equal, defaults to the option that was passed in) |
Returns | number | The item's index or -1 |
Example:
var arr = cjs(['a','b','a']);
arr.indexOf('a'); // 0
Returns the first item where calling filter is truthy
.indexWhere(filter, thisArg) | ||
filter | function | The function to call on every item |
thisArg | * | Object to use as this when executing callback . |
Returns | number | The 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
Convert my value to a standard JavaScript array
.item() | ||
Returns | array | A standard JavaScript array |
.item(key) | ||
key | number | The array index |
Returns | * | The value at index key |
.item(key, value) | ||
key | number | The 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']
Return a constraint whose value is bound to my value for key
.itemConstraint(key) | ||
key | number,Constraint | The array index |
Returns | Constraint | A 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'
The join() method joins all elements of an array into a string.
.join([separator=',']) | ||
[separator=','] | string | Specifies 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. |
Returns | string | The joined string |
Returns the last index of item
.lastIndexOf(item, [equality_check]) | ||
item | * | The item we are searching for |
[equality_check] | function | How to check whether two objects are equal, defaults to the option that was passed in) |
Returns | number | The item's index or -1 |
Example:
var arr = cjs(['a','b','a']);
arr.indexOf('a'); // 2
Returns the last item where calling filter is truthy
.lastIndexWhere(filter, thisArg) | ||
filter | function | The function to call on every item |
thisArg | * | Object to use as this when executing callback . |
Returns | number | The 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
Get the length of the array.
.length() | ||
Returns | number | The length of the array |
Example:
var arr = cjs(['a','b']);
arr.length(); // 2
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) | ||
callback | function | Function that produces an element of the new Array from an element of the current one. |
thisArg | * | Object to use as this when executing callback . |
Returns | array | The result of calling callback on every element |
Example:
var arr = cjs([1,2,3]);
arr.map(function(x) { return x+1;}) // [2,3,4]
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']
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 |
Returns | number | The new length of the array |
Example:
var arr = cjs(['a','b']);
arr.push('c','d'); // 4
arr.toArray(); // ['a','b','c','d']
The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.
.reverse() | ||
Returns | array | A JavaScript array whose value is the reverse of mine |
Change the equality check; useful for indexOf
.setEqualityCheck(equality_check) | ||
equality_check | function | A new function to check for equality between two items in this array |
Returns | cjs.ArrayConstraint | this |
Replaces the whole array
.setValue(arr) | ||
arr | array | The new value |
Returns | cjs.ArrayConstraint | this |
Example:
var arr = cjs([1,2,3]);
arr.toArray(); //[1,2,3]
arr.setValue(['a','b','c']);
arr.toArray(); //['a','b','c']
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']
The slice() method returns a portion of an array.
.slice([begin=0], [end=this.length]) | ||
[begin=0] | number | Zero-based index at which to begin extraction. |
[end=this.length] | number | Zero-based index at which to end extraction. slice extracts up to but not including end. |
Returns | array | A JavaScript array |
Example:
var arr = cjs(['a','b','c']);
arr.slice(1); // ['b','c']
Return true
if filter
against any item in my array is truthy
.some(filter, thisArg) | ||
filter | function | The function to check against |
thisArg | * | Object to use as this when executing filter . |
Returns | boolean | true if some item matches filter . false otherwise |
Example:
var arr = cjs([1,3,5]);
arr.some(function(x) { return x%2===0; }); // false
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] | function | Specifies 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. |
Returns | array | A sofrted JavaScript array |
The splice() method changes the content of an array, adding new elements while removing old elements.
.splice(index, howMany, ...elements) | ||
index | number | Index at which to start changing the array. If greater than the length of the array, no elements will be removed. |
howMany | number | An 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. |
Returns | array.* | 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']
Converts this array to a JavaScript array
.toArray() | ||
Returns | array | This object as a JavaScript array |
Example:
var arr = cjs(['a','b']);
arr.toArray(); // ['a', 'b']
The toString() method returns a string representing the specified array and its elements.
.toString() | ||
Returns | string | A string representation of this array. |
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 |
Returns | number | The new array length |
Example:
var arr = cjs(['a','b','c']);
arr.unshift('x','y'); // 5
arr.toArray(); //['x','y','a','b','c']
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) | ||
options | object |
Stop updating the binding and try to clean up any memory
.destroy() | ||
Returns | undefined |
Pause binding (no updates to the attribute until resume is called)
.pause() | ||
Returns | Binding | this |
Resume binding (after pause)
.resume() | ||
Returns | Binding | this |
Require at least min_delay
milliseconds between setting the attribute
.throttle(min_delay) | ||
min_delay | number | The minimum number of milliseconds between updates |
Returns | Binding | this |
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
Add a transition to my list of transitions that this event is attached to
._addTransition(transition) | ||
transition | Transition | The transition this event is attached to |
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 |
Remove a transition from my list of transitions
._removeTransition(transition) | ||
transition | Transition | The transition this event is attached to |
Create a transition that calls filter whenever it fires to ensure that it should fire
.guard([filter]) | ||
[filter] | function | Returns true if the event should fire and false otherwise |
Returns | CJSEvent | A 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;
});
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
: ifvalue
is a function, the value ofthis
, when that function is called. default:window
equals
: the function to check if two values are equal, default:===
literal
: ifvalue
is a function, the value of the constraint should be the function itself (not its return value). default:false
run_on_add_listener
: whenonChange
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] | Object | A set of options to control how and when the constraint's value is evaluated: |
Absolute value constraint modifier
.abs() | ||
Returns | number | A constraint whose value is Math.abs(this.get()) |
Example:
x = c1.abs(); // x <- abs(c1)
Arccosine
.acos() | ||
Returns | number | A constraint whose value is Math.acos(this.get()) |
Example:
angle = r.div(x).acos()
Addition constraint modifier
.add(...args) | ||
...args | number | Any number of constraints or numbers |
Returns | number | A 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
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 evaluatea
.and(...args) | ||
...args | * | Any number of constraints or values to pass the "and" test |
Returns | cjs.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);
Arcsin
.asin() | ||
Returns | number | A constraint whose value is Math.asin(this.get()) |
Example:
angle = r.div(y).asin()
Arctan
.atan() | ||
Returns | number | A constraint whose value is Math.atan(this.get()) |
Example:
angle = y.div(x).atan()
Arctan2
.atan2(x) | ||
x | number,cjs.Constraint | |
Returns | number | A constraint whose value is Math.atan2(this.get()/x.get()) |
Example:
angle = y.atan2(x)
Bitwise not operator
.bitwiseNot() | ||
Returns | number | A constraint whose value is ~(this.get()) |
Example:
inverseBits = val.bitwiseNot()
Ceil
.ceil() | ||
Returns | number | A constraint whose value is Math.ceil(this.get()) |
Example:
x = c1.ceil(); // x <- ceil(c1)
Cosine
.cos() | ||
Returns | number | A constraint whose value is Math.cos(this.get()) |
Example:
dx = r.mul(angle.cos())
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] | boolean | If set to true , avoids invalidating any dependent constraints. |
Returns | cjs.Constraint | this |
Example:
var x = cjs(1);
x.destroy(); // ...x is no longer needed
Division constraint modifier
.div(...args) | ||
...args | number | Any number of constraints or numbers |
Returns | number | A constraint whose value is this.get() / args[0].get() / args[1].get() / ... |
Example:
x = y.div(1,2,z); // x <- y / 1 / 2 / z
Equals unary operator
.eq(other) | ||
other | * | A constraint or value to compare against |
Returns | boolean | A constraint whose value is this.get() == other.get() |
Example:
isNull = val.eq(null)
Strict equals operator
.eqStrict(other) | ||
other | * | A constraint or value to compare against |
Returns | boolean | A constraint whose value is this.get() === other.get() |
Example:
isOne = val.eqStrict(1)
Exp (E^x)
.exp() | ||
Returns | number | A constraint whose value is Math.exp(this.get()) |
Example:
neg_1 = cjs(i*pi).exp()
Floor
.floor() | ||
Returns | number | A constraint whose value is Math.floor(this.get()) |
Example:
x = c1.floor(); // x <- floor(c1)
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] | boolean | Whether 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
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 |
Returns | cjs.Constraint | A 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);
Change this constraint's value in different states
.inFSM(fsm, values) | ||
fsm | cjs.FSM | The finite-state machine to depend on |
values | Object | Keys are the state specifications for the FSM, values are the value for those specific states |
Returns | cjs.Constraint | this |
Example:
var fsm = cjs.fsm("state1", "state2")
.addTransition("state1", "state2",
cjs.on("click"));
var x = cjs().inFSM(fsm, {
state1: 'val1',
state2: function() { return 'val2'; }
});
Object instance check modifier
.instanceOf(other) | ||
other | * | a constraint or value to compare against |
Returns | boolean | a constraint whose value is this.get() instanceof other.get() |
Example:
var valIsArray = val.instanceof(Array)
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() | ||
Returns | cjs.Constraint | this |
Example:
Tracking the window height var height = cjs(window.innerHeight); window.addEventListener("resize", function() { height.invalidate(); });
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() | ||
Returns | boolean | true 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
Natural Log (base e)
.log() | ||
Returns | number | A constraint whose value is Math.log(this.get()) |
Example:
num_digits = num.max(2).log().div(Math.log(10)).ceil()
Max
.max(...args) | ||
...args | number | Any number of constraints or numbers |
Returns | number | A constraint whose value is the highest of this.get() , args[0].get() , args[1].get() ... |
Example:
val = val1.max(val2, val3);
Min
.min(...args) | ||
...args | number | Any number of constraints or numbers |
Returns | number | A constraint whose value is the lowest of this.get() , args[0].get() , args[1].get() ... |
Example:
val = val1.min(val2, val3);
Multiplication constraint modifier
.mul(...args) | ||
...args | number | Any number of constraints or numbers |
Returns | number | A constraint whose value is this.get() * args[0].get() * args[1].get() * ... |
Example:
x = y.mul(1,2,z); //x <- y * 1 * 2 * z
Negative operator
.neg() | ||
Returns | number | A constraint whose value is -(this.get()) |
Example:
neg_val = x.neg()
Not equals operator
.neq(other) | ||
other | * | A constraint or value to compare against |
Returns | boolean | A constraint whose value is this.get() != other.get() |
Example:
notNull = val.neq(null)
Not strict equals binary operator
.neqStrict(other) | ||
other | * | A constraint or value to compare against |
Returns | boolean | A constraint whose value is this.get() !== other.get() |
Example:
notOne = val.neqStrict(1)
Not operator
.not() | ||
Returns | boolean | A constraint whose value is !(this.get()) |
Example:
opposite = x.not()
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]) | ||
callback | function | |
[thisArg] | * | If specified, only remove listeners that were added with this context |
Returns | cjs.Constraint | this |
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) | ||
callback | function | |
[thisArg=window] | * | The context to use for callback |
...args | * | The first args.length arguments to callback |
Returns | cjs.Constraint | this |
Example:
var x = cjs(1);
x.onChange(function() {
console.log("x is " + x.get());
});
x.set(2); // x is 2
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 evaluateb
.or(...args) | ||
...args | * | Any number of constraints or values to pass the "or" test |
Returns | cjs.Constraint | A constraitn whose value is the first truthy value or false if there aren't any |
Example:
var x = c1.or(c2, c3, false);
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 |
Returns | cjs.Constraint | this |
Coerce an object to a number
.pos() | ||
Returns | number | A constraint whose value is +(this.get()) |
Example:
numeric_val = val.pos()
Power
.pow(x) | ||
x | number | The exponent |
Returns | number | A constraint whose value is Math.pow(this.get(), x.get()) |
Example:
d = dx.pow(2).add(dy.pow(2)).sqrt()
Property constraint modifier.
.prop(...args) | ||
...args | strings | Any 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
Removes every dependency to this node
.remove([silent=false]) | ||
[silent=false] | boolean | If set to true , avoids invalidating any dependent constraints. |
Returns | cjs.Constraint | this |
Signal that this Constraint, which has been paused with pauseGetter
now has a value.
.resumeGetter(value) | ||
value | * | This node's value |
Returns | cjs.Constraint | this |
Round
.round() | ||
Returns | number | A constraint whose value is Math.round(this.get()) |
Example:
x = c1.round(); // x <- round(c1)
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] | Object | A set of options to control how and when the constraint's value is evaluated: |
Returns | cjs.Constraint | this |
Example:
var x = cjs(1); x.get(); // 1 x.set(function() { return 2; }); x.get(); // 2 x.set('c'); x.get(); // 'c'
Change how this constraint is computed (see Constraint options)
.setOption(options) | ||
options | Object | An object with the options to change |
Returns | cjs.Constraint | this |
Example:
var x = cjs(function() { return 1; });
x.get(); // 1
x.setOption({
literal: true,
auto_add_outgoing_dependencies: false
});
x.get(); // (function)
Sine
.sin() | ||
Returns | number | A constraint whose value is Math.sin(this.get()) |
Example:
dy = r.mul(angle.sin())
Square root
.sqrt() | ||
Returns | number | A constraint whose value is Math.sqrt(this.get()) |
Example:
x = c1.sqrt(); // x <- sqrt(c1)
Subtraction constraint modifier
.sub(...args) | ||
...args | number | Any number of constraints or numbers |
Returns | number | A constraint whose value is this.get() - args[0].get() - args[1].get() - ... |
Example:
x = y.sub(1,2,z); // x <- y - 1 - 2 - z
Tangent
.tan() | ||
Returns | number | A constraint whose value is Math.tan(this.get()) |
Example:
dy = r.mul(angle.sin())
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();
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();
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]')
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_names | string | Any number of state names for the FSM to have |
The name of this FSM's active state
Example:
var my_fsm = cjs.fsm("state1", "state2");
my_fsm.state.get(); // 'state1'
Changes the active state of this FSM. This function should, ideally, be called by a transition instead of directly.
._setState(state, transition) | ||
state | State,string | The state to transition to |
transition | Transition | The transition that ran |
Create states and set the current "chain state" to that state
.addState(...state_names) | ||
...state_names | string | Any number of state names to add. The last state becomes the chain state |
Returns | FSM | this |
Example:
var fsm = cjs.fsm()
.addState('state1')
.addState('state2')
.addTransition('state2', cjs.on('click'));
Add a transition between two states
.addTransition(to_state) | ||
to_state | string | The name of the state the transition should go to |
Returns | function | A function that tells the transition to run |
.addTransition(to_state, add_transition_fn) | ||
to_state | string | The name of the state the transition should go to |
add_transition_fn | CJSEvent,function | A CJSEvent or a user-specified function for adding the event listener |
Returns | FSM | this |
.addTransition(from_state, to_state) | ||
from_state | string | The name of the state the transition should come from |
to_state | string | The name of the state the transition should go to |
Returns | function | A function that tells the transition to run |
.addTransition(from_state, to_state, add_transition_fn) | ||
from_state | string | The name of the state the transition should come from |
to_state | string | The name of the state the transition should go to |
add_transition_fn | CJSEvent,function | A CJSEvent or a user-specified function for adding the event listener |
Returns | FSM | this |
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
Remove all of the states and transitions of this FSM. Useful for cleaning up memory
Returns the name of the state this machine is currently in. Constraints that depend on the return value will be automatically updated.
.getState() | ||
Returns | string | The name of the currently active state |
Example:
var my_fsm = cjs.fsm("state1", "state2");
my_fsm.getState(); // 'state1'
Check if the current state is state_name
.is(state_name) | ||
state_name | string | The name of the state to check against |
Returns | boolean | true 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
Remove the listener specified by an on call; pass in just the callback
.off(callback) | ||
callback | function | The function to remove as a callback |
Returns | FSM | this |
Call a given function when the finite-state machine enters a given state.
spec
can be of the form:
'*'
: any state'state1'
: A state namedstate1
'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]) | ||
spec | string | A specification of which state to call the callback |
callback | function | The function to be called |
[context] | object | What this should evaluate to when callback is called |
Returns | FSM | this |
Example:
var x = cjs.fsm("a", "b");
x.on("a->b", function() {...});
Specify which state this FSM should begin at.
.startsAt(state_name) | ||
state_name | string | The name of the state to start at |
Returns | FSM | this |
Example:
var my_fsm = cjs.fsm("state_a", "state_b");
my_fsm.startsAt("state_b");
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] | Object | A set of options to control how the map constraint is evaluated |
Any iterator in forEach can return this object to break out of its loop.
Clear every entry of this object.
.clear() | ||
Returns | cjs.MapConstraint | this |
Example:
var map = cjs({x: 1, y: 2});
map.isEmpty(); // false
map.clear();
map.isEmpty(); // true
Clear this object and try to clean up any memory.
.destroy([silent=false]) | ||
[silent=false] | boolean | If set to true , avoids invalidating any dependent constraints. |
Get every key and value of this object as an array.
.entries() | ||
Returns | array.object | A 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}]
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) | ||
callback | function | Function to execute for each entry. |
thisArg | * | Object to use as this when executing callback . |
Returns | cjs.MapConstraint | this |
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
Get the item at key (like this[key])
.get(key) | ||
key | * | The entry's key |
Returns | *,undefined | the value at that entry or undefined |
Example:
var map = cjs({x: 1, y: 2});
map.get("x"); // 1
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_fn | function | A function to create the value if key is not found |
[create_fn_context] | * | The context in which to call create_fn |
[index=this.size] | number | Where to place a value that is created |
[literal=false] | boolean | Whether to create the value as a literal constraint (the value of a function is the function) |
Returns | number | The 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
Check if there is any entry with key = key
.has(key) | ||
key | * | The key to search for. |
Returns | boolean | true if there is an entry with key=key , false otherwise. |
Example:
var map = cjs({x: 1, y: 2});
map.has('x'); // true
Get the index of the entry with key = key
.indexOf(key) | ||
key | * | The key to search for. |
Returns | number | The index of the entry with key=key or -1 |
Example:
var map = cjs({x: 1, y: 2});
map.indexOf('z'); // -1
Check if this object has any entries
.isEmpty() | ||
Returns | boolean | true if there are no entries, false otherwise |
Example:
var map = cjs({x: 1, y: 2});
map.isEmpty(); // false
Convert my value to a standard JavaScript object. The keys are converted using toString
.item() | ||
Returns | object | A standard JavaScript object |
.item(key) | ||
key | number | The object key |
Returns | * | The value at index key |
.item(key, value) | ||
key | number | The object key |
value | * | The new value |
Returns | cjs.MapConstraint | this |
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']
Return a constraint whose value is bound to my value for key
.itemConstraint(key) | ||
key | *,Constraint | The array index |
Returns | Constraint | A 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
Given a value, find the corresponding key
.keyForValue(value, [eq_check]) | ||
value | * | The value whose key to search for |
[eq_check] | function | How to check if two values are equal (default: === |
Returns | *,undefined | The key where this.get(key)===value |
Example:
var map = cjs({x: 1, y: 2, z: 3});
map.keyForValue(1); // 'x'
Get the keys on this object.
.keys() | ||
Returns | array.* | The set of keys |
Example:
var map = cjs({x: 1, y: 2});
map.keys(); // ['x','y']
Move the entry with key key
to `index
.move(key, to_index) | ||
key | * | The key to search for |
to_index | number | The new index for the key |
Returns | cjs.ArrayConstraint | this |
Example:
var map = cjs({x: 1, y: 2, z: 3});
map.keys(); // ['x','y', 'z']
map.move('z', 0)
map.keys(); // ['z','x', 'y']
Move the entry at old_index
to index new_index
.moveIndex(old_index, new_index) | ||
old_index | number | The index to move from |
new_index | number | The index to move to |
Returns | cjs.ArrayConstraint | this |
Example:
var map = cjs({x: 1, y: 2, z: 3});
map.keys(); // ['x','y', 'z']
map.moveIndex(1, 0)
map.keys(); // ['y','x', 'z']
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] | number | The entry's index |
[literal] | boolean | Whether to treat the value as literal |
Returns | cjs.MapConstraint | this |
Example:
var map = cjs({x: 1, y: 2});
map.put("z", 3, 1);
map.keys(); // ['x','z','y']
Remove a key's entry (like delete this[key]
)
.remove(key) | ||
key | * | The entry's key |
Returns | cjs.MapConstraint | this |
Example:
var map = cjs({x: 1, y: 2});
map.remove("x");
map.keys(); // ['y']
Change the default equality check when getting a key
.setEqualityCheck(equality_check) | ||
equality_check | function | The new key equality check |
Returns | cjs.ArrayConstraint | this |
Change the hash function when getting a key
.setHash(hash) | ||
hash | function,string | The new hashing function (or a string representing a property name for every key to use as the hash) |
Returns | cjs.ArrayConstraint | this |
Change the default value equality check when getting a value
.setValueEqualityCheck(vequality_check) | ||
vequality_check | function | The new value equality check |
Returns | cjs.ArrayConstraint | this |
Change the hash function when getting a value
.setValueHash(hash) | ||
hash | function,string | The new hashing function (or a string representing a property name for every key to use as the hash) |
Returns | cjs.ArrayConstraint | this |
Get the number of entries in this object.
.size() | ||
Returns | number | The number of entries |
Example:
var map = cjs({x: 1, y: 2});
map.size(); // 2
Converts this array to a JavaScript object.
.toObject([key_map_fn]) | ||
[key_map_fn] | function | A function to convert keys |
Returns | object | This object as a JavaScript object |
Example:
var map = cjs({x: 1, y: 2, z: 3});
map.toObject(); // {x:1,y:2,z:3}
Get the values on this object.
.values() | ||
Returns | array.* | The set of values |
Example:
var map = cjs({x: 1, y: 2});
map.values(); // [1,2]