Dynamic Web Development with Seaside

9.2Callbacks

In Seaside, anchors can be used for much more than simple links to other documents. An anchor can be assigned a callback, which is a Smalltalk block (similar to closures or anonymous methods in other languages). When the user clicks on the link, the user’s browser submits a request back to Seaside, which then runs the code in the block (it evaluates the block in Smalltalk terminology).

Here is an example of a component defining a callback which increases the value of the count variable of the component:

WAComponent subclass: #AnchorCallbackExample
instanceVariableNames: 'count'
classVariableNames: ''
poolDictionaries: ''
category: 'SeasideBook-Anchors'
AnchorCallbackExample>>initialize
super initialize.
count := 0.
AnchorCallbackExample>>anchorClicked
count := count + 1
AnchorCallbackExample>>renderContentOn: html
html text: count.
html break.
html anchor
callback: [ self anchorClicked ];
with: 'click to increment'

This method renderContentOn: creates an anchor element by sending WAHtmlCanvas>>anchor to the canvas object (html). The anchor method returns an instance of WAAnchorTag which is then used to set the callback (via the method callback:) and text for this anchor (via the message with:).

When the user clicks on the anchor labelled "click to increment", the callback block is executed: it sends the message anchorClicked to the component which in turn increments the count. Once this callback is processed, Seaside renders our component (which will show the new count).

Register the above application as “anchor” and view it in your browser, see Figure 69. Clicking on the link will increment the count.

Using a callback

Methods on WAAnchorTag Description
url: anUrl Specify a URL to visit when this link is clicked.
callback: aBlock Specify a block that will be invoked when this link is clicked.
with: anObject This specifies the anchor text.

Callback Processing. When Seaside receives a request, it processes all active callbacks and then asks the component to render itself. The order of this process is important. Only when it has completed processing callbacks will it move on to the rendering phase. It will become important to remember this as you build increasingly complicated applications.

Copyright © 19 March 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.