-
Notifications
You must be signed in to change notification settings - Fork 16
Constraint Variables
ConstraintJS relies on constraint variables —-- small wrappers around regular JavaScript objects that allow constraints to be added to them. Any JavaScript object or widget can be turned into a constraint variable using the cjs.constraint
function. For example:
var x = cjs.constraint(1); // x <- 1
Creates x
, a constraint variable whose value is 1
. .get()
fetches the value of a constrainable variable and .set(value)
sets its value:
x.get(); // = 1
x.set(2); // x <- 2
x.get(); // = 2
Dynamically computed variables can be created by passing a function as the parameter:
var y = cjs.constraint(function() {
return x.get() + 1; // y <- x + 1
});
x.get(); // = 2
y.get(); // = 3
x.set(9); // x <- 9
y.get(); // = 10
##Variable Modifiers Constrainable variables also have several built-in utility methods to create new dependent variables. For instance, the declaration of y above may seem cumbersome but the same thing can be achieved with:
y = x.add(1); // y <- x + 1
In this case, .add()
is a built-in function that creates a new constraint variable. Other built-in functions include:
-
.add(...)
— take the sum -
.sub(...)
— take the difference -
.mul(...)
— take the product -
.div(...)
— take the quotient -
.or(...args)
— Returns the first truthy value in the array[this].concat(args)
or `false -
.and(...args)
— Returns the last value in the array[this].concat(args)
if every value is truthy. Otherwise, returnsfalse
. -
.eq(...)
— returns if the constraint variable== x
-
.eqStrict(x)
— returns if the constraint variable=== x
-
.gt(x)
— returns if the constraint variable> x
-
.ge(x)
— returns if the constraint variable>= x
-
.lt(x)
— returns if the constraint variable< x
-
.le(x)
— returns if the constraint variable<= x
-
.round()
— rounds the constraint variable to the nearest integer -
.sin()
— returnsMath.sin(this)
For a full list of modifier functions, see the cjs.Constraint API docs.
[Previous: Using ConstraintJS](Using ConstraintJS)