Chapter 10. Introduction to Scripting

Table of Contents

1. Introduction
2. The <script> tag
2.1. Javascript gotchas
2.2. XML characters in script
3. Functions
4. Methods
4.1. Using Script to manipulate attributes
5. Addressing
6. Methods and arguments
7. Using attributes to reduce complexity

1. Introduction

LZX applications can include procedural code, called Chapter 2, Language Preliminaries as well as declarative XML tags.

Within an LZX program, script can appear

  • between <script> tags

  • between <method> tags

  • between <handler> tags

  • between quotation marks as an assigned value for an attribute

2. The <script> tag

The quickest way to get a script running is to put it in <script> tags. Code in script tags is executed immediately. <script> tags are only embeddable in the <canvas> .

[Note] Note

In the program below, note the debug="true" attribute, which opens up the OpenLaszlo Debugger. In these tutorials we will use the debugger as a scratchpad to illustrate scripting concepts.

Example 10.1. Using the debugger

<canvas width="500" height="200" debug="true">
  <script>
    Debug.write("Hello, World!");
  </script>
</canvas>

We can now use our knowledge of JavaScript to build on this foundation:

Example 10.2. Incorporating JavaScript

<canvas width="500" height="200" debug="true">
  <script>
    // some random scripting
    //
    var someStr = "Hello, World!";
    Debug.write(someStr);
    var first = 4;
    var second = 3;
    var result = first + second;
    Debug.write(result);
   </script>
</canvas>

2.1. Javascript gotchas

If you've never worked with Javascript before, you may be surprised by some subtle features of the language. For example, consider this slight expansion of the preceding program:

Example 10.3. JavaScript subtleties

<canvas width="500" height="200" debug="true">
  <script>
    // some random scripting
    //
    var someStr = "Hello, World!";
    Debug.write(someStr);
    var first = 4;
    var second = 3;
    var result = first + second;
    Debug.write(result);
    Debug.write(first + " plus " + second + " is " + first + second);
    var two = 2;
    if (2 == two) {
      Debug.write("2 is two");
    }
  </script>
</canvas>

Everything there is fine, except the "4 plus 3 is …" line. Four plus three should be 7, as in the line immediately above it, right? What happened is that we concatenated numbers to strings earlier on (4 + " plus " + 3), and that operation converted the numbers to strings.

OpenLaszlo documentation is not intended to provide a complete reference for Javascript. Later chapters do explain some advanced topics in scripting, but we recommend that you have a Javascript reference handy while writing LZX.

2.2. XML characters in script

Let's try a simple "for" loop:

Example 10.4. XML characters cause errors

<canvas height="80" width="500" debug="true">
  <-- the following code will not compile because of the angle bracket -->
  <script>
    for (var i = 0; i < 11; i++) {
      Debug.write(i);
    }
  </script>
</canvas>

Oops!

Because LZX is an XML-based language, there are rules as to what is legal between tags (in particular, <script> tags). The "<" character in the for loop is what is causing the problem. We are not allowed "<" or ">" characters between LZX tags.

Fortunately there are ways around this.

[Note] Note

The next two examples are not interactive, but they are correct LZX programs

Example 10.5. Encoding XML characters

<canvas height="120">
   <script>
     for (var i = 0; i &lt; 11; i++) {
       Debug.write(i);
     }
   </script>
</canvas>

Example 10.6. Using CDATA

<canvas height="120">
   <script>
     <![CDATA[
     for (var i = 0; i < 11; i++) {
       Debug.write(i);
     }
     ]]>
   </script>
</canvas>

Either of the above two methods will work. Whichever you use is up to you, and of course the particular application. The CDATA method is perhaps a little more practical for larger blocks of code.

3. Functions

You can write functions in <script> tags.

Example 10.7. Javascript functions

<canvas height="200" width="500" debug="true">
  <script>
    <![CDATA[
    // write a word to the debugger
    //
    function writeAWord(someWord) {
      Debug.write(someWord);
    }
    
    writeAWord("HELLO!");
    ]]>
  </script>
</canvas>

Functions are global to the LZX document, and they follow the same scope rules as JavaScript.

4. Methods

Methods are in some ways similar to functions. They contain blocks of code between <method> tags, and are associated with particular classes. In the Chapter 8, Introduction to Media and Art Assets tutorial, we saw a few methods of the LzView class that pertain to resources:

  • play()

  • stop()

  • getOffset()

  • getMaxOffset()

Let's explore methods with a simple example of a window. The <window> element is actually a view, as we saw before. There are a few methods that apply to it. The window class extends LzView class. This means that windows inherit all the attributes and methods of views.

Example 10.8. a simple method

<canvas height="200" width="500">
  <window x="20" y="20" width="150"
          title="Simple Window" resizable="true">
    <button text="My button" 
            onclick="this.parent.setAttribute('title', 'You clicked it');"/>
  </window>
</canvas>

Let's break this statement apart:

    onclick="this.parent.setTitle('You clicked it');"

First, there's the

    onclick=

Like all of the on[event] attributes, this one takes JavaScript that will be run in the context of the object when the event is received.

The next part:

    this.parent

is a reference to an object. In Javascript, the scope is generally global unless you say otherwise. That means that any class or instance methods or variables must be preceded by the keyword this. As for the 'parent' part: Let's start by saying that the lzx viewsystem always assigns each view a variable 'parent' which points to that view's hierarchical parent. View hierarchies are discussed in detail in Chapter 26, Views

Now we're going to call a method. With very few exceptions, tags in an lzx file correspond to run-time objects of the view system. Using xml, we can configure those objects with attributes and child nodes. Using script, we can call their APIs. From the documentation, we know that the <window> has a setTitle() method that will change the window title to whatever string you give it.

The last thing to note is the use of single quotes inside the function call.

4.1. Using Script to manipulate attributes

Remember that window extends the LzView class. That means that each window has all the attributes of a <view> . Here's an example of how to use script to manipulate some of those assets.

Example 10.9. Manipulating <view> attributes

<canvas width="500" height="200">
  <window x="100" y="30" 
          title="Window 2" name="windowTwo">
    <text>This is the second window.</text>
  </window>
  <window x="20" y="20" width="150"
          title="Simple Window">
    <button text="My button" 
            onclick="this.parent.parent.windowTwo.setAttribute('x', 200)"/>
  </window>
</canvas>

We're just building on the previous example here. Instead of addressing the parent view of the button, we are going two up, then one down. this.parent.parent refers to the canvas, and we point to Window 2 by using its name (windowTwo).

We are also using the setAttribute() method, which takes two arguments: the attribute to set, and what to set it to.

Next, let's find a way to move Window 2 over so that we can see what's behind it, without dragging it. Clicking the button twice doesn't help, because all that does is reset the x attribute to a constant amount (150px).

Instead, we need to figure out where the second window is, and then add an increment to it each time the button is clicked. Looking again at the API reference for the LzView class, we can see that there is a getAttribute() method to get the x attribute.

So we could say:

Example 10.10. getting attributes

<canvas width="500" height="200">
  <window x="100" y="30" 
          title="Window 2" name="windowTwo">
    <text>This is the second window.</text>
  </window>
  <window x="20" y="20" width="150"
          title="Simple Window">
    <button text="My button" 
            onclick="this.parent.parent.windowTwo.setAttribute('x',
            this.parent.parent.windowTwo.getAttribute('x') + 20)"/>
  </window>
</canvas>

That works, but the code is getting pretty messy. It would be more elegant to encase all the code in a block and call it whenever the button is clicked…. To do what, we could write a function:

Example 10.11. Moving window by function call

<canvas width="500" height="200">
  <script>
    // Moves the second window twenty pixels to the right
    //
    function moveWindow() {
      var increment = 20;
      var originalX = canvas.windowTwo.getAttribute('x');
      var newX = originalX + increment;
      canvas.windowTwo.setAttribute('x', newX);
    }
  </script>
  <window x="100" y="30" 
          title="Window 2" name="windowTwo">
    <text>This is the second window.</text>
  </window>
  <window x="20" y="20" width="150"
          title="Simple Window">
    <button text="My button" 
              onclick="moveWindow();"/>
  </window>
</canvas>

Notice how we use the "canvas." syntax for pointing to the second window. We have to address the view absolutely. The code is a lot easier to understand, because we can break it up over several lines, comment it and assign appropriately-named variables.

However, the function is pretty detached from the button. A more elegant way of achieving the same result would be to write a method of the button.

Example 10.12. From function to method

<canvas width="500" height="200">
  <window x="100" y="30" 
          title="Window 2" name="windowTwo">
    <text>This is the second window.</text>
  </window>
  <window x="20" y="20" width="200"
          title="Simple Window">
    <button text="My button" onclick="this.moveWindow()">
      <!-- Moves the second window twenty pixels 
           to the right -->
      <method name="moveWindow">
        var increment = 20;
        var originalX = this.parent.parent.windowTwo.getAttribute('x');
        var newX = originalX + increment;
        this.parent.parent.windowTwo.setAttribute('x', newX);
      </method>
    </button>
  </window>
</canvas>

Since methods are not not global, we have to call them relatively. In the case of the button, we use this.moveWindow(). In theory we could have a second button that, when clicked, would call a method of the first button. The only difference would be the addressing. Before we go any further with methods, let's take a proper look at addressing:

5. Addressing

In LZX, objects can have names and/or ids by which they can be addressed. A name needs to be referred to locally, so there can be more than one view with the same name in a file (they just can't be siblings). An id is global, so there can't be two views with the same id in a LZX file.

Going back to the idea of having one button call the second button's method:

Example 10.13. One button calls another's method

<canvas width="500" height="200">
  <window x="100" y="60" 
          title="Window 2" name="windowTwo">
    <text>This is the second window.</text>
  </window>
  <window x="20" y="20" width="210"
          title="Simple Window">
    <simplelayout axis="x" spacing="4"/>
    <button text="My button" name="button1" 
            onclick="this.moveWindow()">
      <!-- Moves the second window twenty pixels 
           to the right -->
      <method name="moveWindow">
        var increment = 20;
        var originalX = this.parent.parent.windowTwo.getAttribute('x');
        var newX = originalX + increment;
        this.parent.parent.windowTwo.setAttribute('x', newX);
      </method>
    </button>
    <button text="Bigger Button" 
            onclick="this.parent.button1.moveWindow()"/>
  </window>
</canvas>

Both buttons now cause the window to move. However, it's confusing that one button points to a method in another button. Since windowTwo is doing the moving, why not make the method part of the window, and have both buttons point to that? Instead of addressing it with the whole this.parent… dot syntax, we can give it an id, and access it globally:

Example 10.14. Using the <ID> tag

<canvas width="500" height="200">
  <window x="100" y="60" 
          title="Window 2" name="windowTwo" id="windowTwoId">
    <!-- Moves the second window twenty pixels 
         to the right -->
    <method name="moveWindow">
      var increment = 20;
      var originalX = this.getAttribute('x');
      var newX = originalX + increment;
      this.setAttribute('x', newX);
    </method>
    <text>This is the second window.</text>
  </window>
  <window x="20" y="20" width="210"
      title="Simple Window">
    <simplelayout axis="x" spacing="4"/>
    <button text="My button" name="button1" 
            onclick="windowTwoId.moveWindow()"/>
    <button text="Bigger Button" 
            onclick="this.parent.parent.windowTwo.moveWindow()"/>
  </window>
</canvas>

Just to illustrate ids and names, one button is addressing the window relatively using its name, and the other globally, using its id. Note that the id and name could have been the same, they were intentionally different in this example.

6. Methods and arguments

In the forgoing example we have two buttons that do the same thing. Why not make them do different things? Move the box left and right, perhaps? We might write another method to move the box to the left, but it would be more elegant to use the same method for both directions. Just as with functions, we can pass arguments to methods.

Here's one possible solution:

Example 10.15. methods and arguments

<canvas width="500" height="200">
  <window x="100" y="60" 
          title="Window 2" name="windowTwo" id="windowTwoId">
    <!-- Moves the second window twenty pixels 
         in specified direction -->
    <method name="moveWindow" args="direction">
      // decide which direction to go
      if (direction == "left") {
       var increment = -20;
      } else if (direction == "right") {
        var increment = 20;
      }
      var originalX = this.getAttribute('x');
      var newX = originalX + increment;
      this.setAttribute('x', newX);
    </method>
    <text>This is the second window.</text>
  </window>
  <window x="20" y="20" width="210"
      title="Simple Window">
    <simplelayout axis="x" spacing="4"/>
    <button text="Move Left" name="button1" 
            onclick="windowTwoId.moveWindow('left')"/>
    <button text="Move Right" 
            onclick="windowTwoId.moveWindow('right')"/>
  </window>
</canvas>

We can pass more than one argument to a method, just as with a function:

Example 10.16. Passing multiple arguments to a method

<canvas width="500" height="200">
  <window x="100" y="60"
          title="Window 2" name="windowTwo" id="windowTwoId">
    <!-- Moves the second window twenty pixels 
         in specified direction -->
    <method name="moveWindow" args="direction, distance">
      // decide which direction to go
      if (direction == "left") {
        var increment = -1 * distance;
      } else if (direction == "right") {
        var increment = distance;
      }
      var originalX = this.getAttribute('x');
      var newX = originalX + increment;
      this.setAttribute('x', newX);
    </method>
    <text>This is the second window.</text>
  </window>
  <window x="20" y="20" width="300"
      title="Simple Window">
      <simplelayout axis="x" spacing="4"/>
      <button text="Left 2" name="button1" 
              onclick="windowTwoId.moveWindow('left', 2)"/>
      <button text="Left 20" name="button2" 
              onclick="windowTwoId.moveWindow('left', 20)"/>
      <button text="Right 20" 
              onclick="windowTwoId.moveWindow('right', 20)"/>
      <button text="Right 2" 
              onclick="windowTwoId.moveWindow('right', 2)"/>
  </window>
</canvas>

7. Using attributes to reduce complexity

Continuing from the same example as above, let's look at ways to reduce the number of arguments being passed. Here we put the functionalilty into the button itself:

Example 10.17. More on attributes

<canvas width="500" height="200">
  <window x="100" y="60"
        title="Window 2" name="windowTwo" id="windowTwoId">
    <!-- Moves the second window specified number of pixels 
         in specified direction -->
    <method name="moveWindow" args="buttonObj">
      direction = buttonObj.getAttribute("direction");
      distance = parseInt(buttonObj.getAttribute("distance"));
      // decide which direction to go
      if (direction == "left") {
       var increment = -1 * distance;
      } else if (direction == "right") {
        var increment = distance;
      }
      var originalX = this.getAttribute('x');
      var newX = originalX + increment;
      this.setAttribute('x', newX);
    </method>
    <text>This is the second window.</text>
  </window>
  <window x="20" y="20" width="300"
      title="Simple Window">
    <simplelayout axis="x" spacing="4"/>
    <button onclick="windowTwoId.moveWindow(this)">Left 2
      <attribute name="direction" value="'left'"/>
      <attribute name="distance" value="'2'"/>
    </button>
    <button onclick="windowTwoId.moveWindow(this)">Left 20
      <attribute name="direction" value="'left'"/>
      <attribute name="distance" value="'20'"/>
    </button>
    <button onclick="windowTwoId.moveWindow(this)">Right 20
      <attribute name="direction" value="'right'"/>
      <attribute name="distance" value="'20'"/>
    </button>
    <button onclick="windowTwoId.moveWindow(this)">Right 2
      <attribute name="direction" value="right" type="string"/>
      <attribute name="distance" value="'2'"/>
    </button>
  </window>
</canvas>

The buttons have attributes which we have named "distance" and "direction". The values of those attributes need to be in double quoted strings, because the value needs to be a JavaScript expression, not a string or a number. That's the reason for the value="''".

Alternatively we could give the <attribute> tag an attribute type="string", as shown in the "right 2" button. In this case the word "right" does not need to be single-quoted.

This example is actually more lengthy than the previous one, but it demonstrates the power of object oriented programming in LZX. If the number of attributes were to grow, and if various buttons had different attributes, the code would still remain very clear.