Dynamic Web Development with Seaside

5.4Developing your first component

To illustrate the above points, we will go through the initial steps of developing the Counter example in GNU Smalltalk. We’ll use a slightly different name so we won’t conflict with the example already loaded with Seaside.

Place the following code in a file:

Seaside.WAComponent subclass: WebCounter [
    | count |
    WebCounter class >> canBeRoot [ ^true ]

    initialize [
        super initialize.
        count := 0.
    states [ ^{ self } ]
    renderContentOn: html [ html heading: count ]
WebCounter registerAsApplication: 'webcounter'

You can see that, apart from some syntactic sugar, the above is just Smalltalk as in any other dialect, except that method bodies are surrounded by square brackets. count declares an instance variable.

Here are the few concepts that the above basic component highlights:

  • A Seaside component, is defined by a subclass of WAComponent class. Accordingly, to create a component, the above file creates the corresponding class.
  • Each component is responsible for rendering itself in the web browser. This is done in Seaside by implementing a renderContentOn: method. In this simple case, that means displaying the counter value.
  • Registering the application with Seaside makes its entry point is accessible at a URL path.

Registering an application is done in two steps. First, we must declare that our application component can be a root component, by defining a WAComponent class>>canBeRoot class method. Second, we must register the component as an application, which is done by the final line of the file. Code that is outside a class declaration corresponds to a doit (or, if you are not coming from Smalltalk, is just evaluated as the file is parsed).

After loading the code in a running server:

$ gst-remote --file Counter.st

the application will be visible at http://localhost:8080/seaside/webcounter. At the moment however it is pretty boring, so we improve the WAComponent>>renderContentOn: method like this:

    renderContentOn: html [
        html heading: count.
        html anchor callback: [ count := count + 1 ]; with: '++'.
        html space.
        html anchor callback: [ count := count - 1 ]; with: '--'.

Reload the code in the server using the same gst-remote invocation as above. Go back to the web browser and refresh the page: there are now two anchors with increment (++) and decrement (—) links that call back to the actions.

Click the new links a few time to verify that it works. That’s it. You developed your first Seaside component.

Copyright © 21 April 2024 Stéphane Ducasse, Lukas Renggli, C. David Shaffer, Rick Zaccone
This book is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 license.

This book is published using Seaside, Magritte and the Pier book publishing engine.