Using the applyConstraint Method

Just as you can use delegates to wire event with an event handler at runtime, you can set a constraint to an object’s attribute after the object is created. You may also want to do this if the expression in long and does not fit in a single line.

To achieve this, you use the applyConstraint method of the LzNode class. This method has the following signature.

applyConstraint(property, function, dependencies)

where property is the attribute to be assigned the constraint, function is the function that sets the attribute to the value, and dependencies is an array of reference/attribute pairs that the constraint depends on.

For example, revisit the LZX application in Listing 6.1, reprinted here for your reading convenience.

<canvas>
    <text x="110" text="${win.x}"/>
    <window id="win" width="100" height="100"/>
</canvas>

The code in Listing 6.6 rewrites the code in Listing 6.1 to apply a constraint at runtime.

Listing 6.6. Applying a constraint at runtime
<canvas>
    <text x="110">
        <method event="oninit">
            var f = function() {
                this.setAttribute("text", win.x)
            }
            var d = [win, "x"];
            this.applyConstraint("text", f, d);
        </method>
    </text>
    <window id="win" width="100" height="100"/>
</canvas>

Now the text tag does not have a constraint assigned to its text attribute. However, it now has a method that will be invoked when the text tag is initialized. The method defines a function called f:

var f = function() {
    this.setAttribute("text", win.x)
}

This sets the text attribute with the value of win.x, which is the x attribute of win.

The method also defines an array of dependencies (d):

var d = [win, "x"];

Lastly, the method calls the applyConstraint method of the text component:

this.applyConstraint("text", f, d);

This effectively sets a constraint to the text attribute of the text tag.

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

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