Skip to content

The counter example

Oscar Nierstrasz edited this page Dec 5, 2013 · 3 revisions

This tutorial will teach you how to build HTML with Amber using jQuery and the HTMLCanvas API. It is freely adapted from the Seaside counter example

##The counter widget

The counter is the most basic example of a widget. It allows to increment and decrement a number by clicking a button.

Amber already comes with a counter example in the Examples package. To avoid class name conflict, we'll name our counter class TCounter.

Widget subclass: #TCounter
    instanceVariableNames: 'count header'
    package: 'Tutorials'

The first method is used to initialize the component with the default state, in this case we set the counter to 0:

initialize
    super initialize.
    count := 0

The method used for rendering a widget is #renderOn:. It takes an instance of HTMLCanvas as parameter. The header h1 is kept as an instance variable, so when the count value changes, we can update its contents accordingly.

renderOn: html
    header := html h1 
        with: count asString;
        yourself.
    html button
        with: '++';
        onClick: [self increase].
    html button
        with: '--';
        onClick: [self decrease]

The counter is almost ready. All we need now is to implement the two action methods #increase and #decrease to change the state of our counter and update its header.

increase
    count := count + 1.
    header contents: [:html | html with: count asString]

decrease
    count := count - 1.
    header contents: [:html | html with: count asString]

That's it! We can now display an instance of TCounter by rendering it on the page using jQuery:

TCounter new appendToJQuery: 'body' asJQuery
Clone this wiki locally