Pages

Monday, April 19, 2010

Using block to invoke client Javascript code in Tapestry 5

In my previous post  I've been able to create a self updating tapestry zone.But its only halfway of what i want to do. Although I already give 2 button to start and stop the timer, i want it to be more automatic.Simply said, the server need to send a response that will trigger the stopTimer js function when the crawling process is finished.

To do this I'm using 2 block. The first block contain the regular content that will be returned from the server. While the second block contains the content and an embedded javascript that will invoke the stopTimer function in the client browser. This is the changes I made to my previous post.

The Code

Template Code :
        <t:zone t:id="infoZone" t:update="show">   
        </t:zone><br/>
       
        <t:block id="info">
            Updating Message ....
            <p t:type="OutputRaw" t:value="${message}">
                Text Output
            </p>
        </t:block>

        <t:block id="infoWithScript">
            Update Stopped
            <p t:type="OutputRaw" t:value="${message}">
                Text Output
            </p>
            <script type="text/javascript">
                stopTimer();
            </script>
        </t:block>

    <a t:type="actionlink" t:id="crawl" href="#">Start Crawl</a> &nbsp;

In the template code I'm adding the two block named "info" and "infoWithScript". The block will not be rendered by default. And also I added another actionlink that will change the state in the server and start the crawling process.

Changes in java code :
    @Inject
    private Block _info;
   
    @Inject
    private Block _infoWithScript;

    Object onActionFromRefreshZone() {
        if(crawler.getCrawlStatus() == Crawler.CRAWL_STARTED) {
            crawler.setCrawlStatus(Crawler.CRAWL_CRAWLING);
            crawler.updateData(URL);
        }
       
        if(crawler.getCrawlStatus() == Crawler.CRAWL_END) {
            crawler.setCrawlStatus(Crawler.CRAWL_IDLE);
            return _infoWithScript;
        }
        return _info;
    }

    void onActionFromCrawl() {
        crawler.setCrawlStatus(Crawler.CRAWL_STARTED);
    }

    public String getMessage() {
        return ProgressNotifier.getMessage();
    }

In the java code we add the two block that will be return by onActionFromRefrezhZone. This method will check if the crawl status in our services class is changed to started, then it will execute update data (the method that will invoke the real process and add messages to the ProgressNotifier).

At the end of the updateData method, the crawl status will be set to CRAWL_END. So the onActionFromRefreshZone will return the block that contain the embedded js to turn off the timer. And return the status to the original CRAWL_IDLE state.

Nothing changes in the client js script.

~FD

No comments: