Friday, March 9, 2012

Events in Smart Devices objects

In the Smart Devices objects (Panels and WorkWith) you can write events as you would normally do in any GeneXus object. However, due to the differences between platforms, the way events are triggered is not the same as in Win or Web objects.

When you generate a smart device object in GeneXus, it creates the client component that runs on the device, but also some services that run on the server.

The events, programmed in the smart devices object, may be executed in the server or in the client, based on some rules:
  • the Start event runs on the server, the first time the object is shown on screen (in the device)
  • the Refresh event runs on the server, every time there is a refresh triggered on the client (by calling the refresh command or whenever it is called automatically)
  • the Load event runs on the server, and is called immediately after the Refresh event, with the difference that it is used to modify Grid variables.
  • every other user event is executed on the client device.
Regarding user events, even though the event runs on the client device, it may need to send requests to the server. For instance, when you call a procedure, the procedure runs on the server.

Having said so, there are a few tips we can give you.

Tip 1: don't call two procedures in the same event

In some cases, you may want to write the following code:
Event 'SomeUserEvent'
    Composite
        Procedure1(...)
        Procedure2(...)
    EndComposite
EndEvent
This wil perform two server requests, one for each procedure. This is an expensive operation and should be avoided when possible. Instead, write
Event 'SomeUserEvent'
    Procedures1and2(...)
EndEvent
and make Procedures1and2 call Procedure1 and Procedure2. This is better because there will be only one request to the server.

Tip 2: move as many code as you can to the Refresh or Load events

Suppose you need to initialize a certain variable, that will be used in a user event. You may write something like
Event 'SomeUserEvent'
    Composite
        &MyVar = InitalizeVariable()
        DoSomething(&MyVar)
    EndComposite
EndEvent
However, if the initialization doesn't depend on any information from the client device, it is better to make the call in the Refresh or Load event, because it avoids making a new server request. The code may look like this:
Event Refresh
    &MyVar = InitalizeVariable()
EndEvent

Event 'SomeUserEvent'
    DoSomething(&MyVar)
EndEvent
Tip 3: execute device-dependent initialization code in the caller object

The Start and Refresh events are executed in the server, so it is not possible to access device information (geo location, for example) when executing those events.

If you need to have that information available in the Start or Refresh events, you should pass them as parameters to the smart device object.