Embedthis Ejscript 1.1.2
Home > Language Guide > Events

Quick Nav

See Also

Eventing

Ejscript has an efficient eventing framework to support asynchronous programming. It consists of event dispatchers, listening objects, event objects and timers.

The Ejscript event service allows event queues to be created and for interested parties to listen for events of interest. Events objects can then be sent to the event dispatcher and relayed onto subscribing listeners. This implements the classic Publish and Subscribe pattern.

Event Dispatcher

An event dispatcher is responsible for managing an event queue and for dispatching events to all registered listening objects. Event dispachers are created by instantiating the Dispatcher class. Applications can create any number of event dispatchers.

var events = new Dispatcher

Once created, the Dispatcher instance can be used by interested parties who wish to "listen" for events. They do this by invoking the addListener Dispatcher method and supplying a callback function to invoke to receive the event.

function callback(e: Event) { print("Got event " + e) } events.addListener(callback)

In this example we pass in a global callback function. However, you can also pass in an object method.

myObj.callback = function (e) {
    print("Got event " + e)
}
events.addListener(callback)

When you pass in an object method you do not also need to pass in an object reference, Ejscript intelligently captures a reference to the object that owns the method — in this case, the myObj object reference. This process is called method binding.

Dispatching Events

An event is dispatched to listening parties by calling the dispatch method of the Dispatcher object.

events.dispatch(new Event("Sunny Day"))

When dispatch is called, the event is passed to all listening parties who will have their registered callback function invoked with the supplied event as the actual parameter.

Scheduling Timers

Ejscript also supports timer events which can be scheduled to run after a given delay.

function callback(e) {
    e.data.stop()
}   
var t = new Timer(10 * 1000, callback)      //  Set timer to run every 10 seconds
App.serviceEvents(60 * 1000)                // Wait for timer to run

A timer event will not be run unless the application is waiting in either App.serviceEvents, App.sleep or otherwise waiting in the Ejscript main event loop.

© Embedthis Software LLC, 2003-2012. All rights reserved. Embedthis, Ejscript and Appweb are trademarks of Embedthis Software LLC.