Introduction to Constraints

A constraint can be assigned to a tag’s attribute. Its syntax is as follows.

$when{expression}

Here, expression is a JavaScript expression and when is one of the following compiler directives: immediately, once, or always, $always{expression} can be written as ${expression}.

For example, the LZX application in Listing 6.1 uses a constraint as the value of the text attribute of a text component.

Listing 6.1. Using a constraint
<canvas>
    <text x="110" text="${win.x}"/>
    <window id="win" width="100" height="100"/>
</canvas>

The constraint in this case is:

${win.x}

win.x is an expression, representing the value of the x attribute of win, a Window component. You can compile this application by directing your browser here:

http://localhost:8080/lps-4.0.x/app06/constraintTest1.lzx

The text and the window are shown in Figure 6.1.

Figure 6.1. Using a constraint


Initially, the value of the x attribute is 0, however if you drag the window, the value of x will change and the change is reflected in the text.

As another example, consider the LZX application in Listing 6.2.

Listing 6.2. Using constraint to follow mouse move
<canvas>
    <view y="0" bgcolor="0xbbccdd" height="4"
            width="${parent.width}">
        <view width="4" height="4" bgcolor="red"
            x="${parent.parent.getMouse('x')}"/>
    </view>
</canvas>

You can use this URL to compile and run the example.

http://localhost:8080/lps-4.0.x/app06/constraintTest2.lzx

Figure 6.2 shows the application.

Figure 6.2. Following the mouse motion


The small red view in Figure 6.2 follows your mouse movement because its x attribute is assigned this constraint:

${parent.parent.getMouse('x')}

That is another constraint in action.

The code in Listing 6.3 shows another example of using a constraint. This time a slider is used to control the opacity of a view.

Listing 6.3. Controlling opacity
<canvas height="300" width="700">
    <view bgcolor="red" id="display" width="200" height="200"
            opacity="${parent.adjuster.value/100}"/>
    <slider x="0" y="200" name="adjuster" value="100"/>
</canvas>

We assign the following constraint to the opacity attribute of the view in Listing 6.3:

opacity="${parent.adjuster.value/100}"

The opacity value will then change according to the value of the slider. You can use this URL to compile and run the example:

http://localhost:8080/lps-4.0.x/app06/constraintTest3.lzx

Figure 6.3 shows the generated output. Drag the slider and witness how the view’s opacity changes.

Figure 6.3. Controlling opacity


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset