Working with Custom Attributes

You can use an attribute in your LZX application. The attribute will act as a global variable that can be accessed from anywhere in the code. For example, the code in Listing 12.7 shows the use of the attribute inside the canvas tag.

Listing 12.7. Using custom attributes
<canvas width="200">
    <reverselayout axis="x"/>
    <attribute name="counter" type="number" value="1"/>
    <button text="Increment">
        <method event="onclick">
            var oldValue = parent.getAttribute("counter");
            parent.setAttribute("counter", oldValue + 1);
        </method>
    </button>
    <text name="my" text="${parent.counter}"/>
</canvas>

Note from Listing 12.7 that to read an attribute, you use the getAttribute method. To assign a value, use the setAttribute method.

An attribute can have a type. In the code in Listing 12.7 the type attribute of the attribute tag is used to define the attribute type. The following are attribute types in OpenLaszlo.

  • string

  • number

  • text

  • html

Normally, your custom attributes have the number or string type. However, if the attribute is named text, you may use the text or html type for it.

The text and html types are special because it allows you to assign an attribute value by passing the value as an element’s value, in addition to the normal way of setting an attribute value. For example, the text attribute of the text tag is of type html. As such, you can set the value of the text tag’s text attribute this way:

<text name="idl">This is a description</text>

which has the same effect as

<text name="idl" text="This is a description"/>

The advantage of using the text type is you can assign a long string conveniently. You do not even need to escape strings that contain double quotes.

For example, to assign the string John “The Great” O’Connor to a text attribute of the myclass tag, you can write

<myclass>John "The Great" O'Connor</myclass>

If you are to assign it the normal way, you would have to change the double quotes in the string to its entity code (&quot;).

<myclass text="John &quot;The Great&quot; O'Connor"/>

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

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