Iliad applications with Comet

Tagged:  •  

Iliad 0.8 features a Comet implementation using XmlHttpRequest long polling. In this post I'll explain here how to build a very simple Comet application with a counter.

Application instances will share the same counter model. Comet counter widgets are similar to the counter example widget, except that they will register to comet events, and trigger them when the count value changes, pretty much like announcements.

When a comet event is triggered, all widgets which registered to the event class will be rebuilt.

So first of all we need to create a subclass of ILCometEvent:

ILCometEvent subclass: ILCounterChangedEvent []

Now the counter model. Widgets will access the model with ILCounterModel class>>instance.

ILObject subclass: ILCounterModel [
    | count |

    ILCounterModel class [
        | instance |
        
        instance [
            instance ifNil: [instance := self new].
            ^instance
        ]
    ]

    initialize [
        super initialize.
        count := 0
    ]

    count [
        ^count
    ]

    increase [
        count := count + 1
    ]

    decrease [
        count := count -1
    ]
]

Finally, the counter widget. All we have to do to handle comet events is to subscribe the widget with #subscribeToCometEvent:. Widgets can also decide what do when a comet event is triggered with #handleCometEvent:. The default behavior is to mark the widget dirty.

Iliad.ILWidget subclass: ILCometCounter [
    | counter |

    initialize [
        super initialize.
        counter := ILCounterModel instance.
        self subscribeToCometEvent: ILCounterChangedEvent
    ]

    contents [
        ^[:e |
            e h1: counter count printString.
            e a action: [self increase]; text: '++'.
            e a action: [self decrease]; text: '--']
    ]

    increase [
        counter increase.
        self markDirty.
        self triggerCometEvent: ILCounterChangedEvent new
    ]

    decrease [
        counter decrease.
        self markDirty.
        self triggerCometEvent: ILCounterChangedEvent new
    ]
]

That's all :) Note that comet events are only pushed to other sessions, so you still need to mark your widget dirty if you want it to be rebuilt.

You can try the comet counter widget with a simple application:

ILApplication subclass: ILCometCounterApplication [
    | counter |    

    ILCometCounterApplication class >> path [^'examples/comet']

    initialize [
        super initialize.
        counter := ILCometCounter new
    ]

    index [
        <category: 'controllers'>
        ^[:e |
            e 
                build: self cometConnection; 
                build: counter]
    ]
]

This example is included in Iliad in the category Iliad-More-Examples.

Happy Iliad hacking!

User login