Tuesday, February 28, 2006

Where can you create a delegate? What is "this" in the script tag?

I needed a little timer function in Laszlo. I modified the Laszlo LzTimer demo to produce this:


<canvas height="100%" width="100%" debug="true">
  <attribute name="counter" type="number" value="10"/>
  <simplelayout axis="y" spacing="2" />
  <button text="start countdown" onclick="canvas.countdown(10)" />
  <text name="myText" width="${parent.width}"/>

  <script>
   Debug.write("doing countDelegate");
   this.countDelegate = new LzDelegate( this, "countdownText" );
  </script>

  <method name="countdown" args="val">
   Debug.write("countdown method with val = " + val);
   this.counter = val ;
   LzTimer.addTimer( this.countDelegate, 1000 );
  </method>

  <method name="countdownText">
   <![CDATA[
   Debug.write("doing countdownText " + this.counter);
   this.myText.setText( this.counter );
   if ( this.counter > 0 ) {
    LzTimer.resetTimer(this.countDelegate, 1000);
    this.counter--;
    Debug.write("decremented counter " + this.counter);
   }
   ]]>
  </method>
</canvas>

The code doesn't work as intended, and I get a warning on clicking the button: "WARNING: test_timer.lzx:15: reference to undefined property 'countDelegate'".

If I move the line this.countDelegate = new LzDelegate(this, "countdownText" ); from within the script tags into the countdown method, the application works correctly. If I had strictly followed the Laszlo demo, this is where I would have placed the LzDelegate constructor to begin with.

I can see from the debugging output that the script code is being run initially, so I don't understand why I'm getting this error. Maybe there's no "this" when the code within script is called? I'm off to investigate.


And I'm back. I added a little debugging code and found that in the script tag, "this" is printed as "[object Object]", while in method countdown, "this" is printed as "canvas". That's a clue, anyway.

0 Comments:

Post a Comment

<< Home