Blog

Custom events, Direct invocation of custom server-side code

by on July 7, 2014

In addition to the built-in events triggered by the API calls, Backendless supports custom, developer-defined events. Custom business logic code, which is executed on the server-side, can be attached to either built-in events or the developer-defined ones. Custom events can be triggered through a specialized API call from a client library or by other custom business logic. Dispatching a custom event may have event arguments. The server-side code that handles an event may also return a value to be delivered back to the client-side that dispatched the event. This feature can be used to invoke custom business logic from the client-side.

Developing custom event handlers is very easy with Backendless – you can register an event using Backendless console, which automatically generates the source code required for declaring an event handler. Just like with the built-in events, custom event handlers can be debugged on the developer machine before the code is pushed to production.

The client-side API for dispatching an event is trivially simple. For all implementations (Android, iOS, JS, AS and .NET) it is a one-liner where you specify event name and event arguments.

Here’s an example of the most simple implementation of custom event handler:

package com.backendless.servercodedemo.events.custom_events;
import com.backendless.servercode.RunnerContext;
import com.backendless.servercode.annotation.Asset;
import com.backendless.servercode.annotation.Async;
import com.backendless.servercode.annotation.BackendlessEvent;
import com.backendless.servercode.annotation.BackendlessGrantAccess;
import com.backendless.servercode.annotation.BackendlessRejectAccess;
import com.backendless.servercode.extension.CustomEventHandler;
import java.util.Collections;
import java.util.Map;
/**
* FooEventHandler handles custom event "foo". This is accomplished with the
* BackendlessEvent( "foo" ) annotation. The event can be raised by either
* the client-side or the server-side code (in other event handlers or timers).
* The name of the class is not significant, it can be changed, since the event
* handler is associated with the event only through the annotation.
*/
@BackendlessEvent( "foo" )
public class FooEventHandler extends CustomEventHandler
{
 @Override
 public Map handleEvent( RunnerContext context, Map eventArgs )
 {
   // add your code here
   return Collections.emptyMap();
 }
}

The @BackendlessEvent annotation declares the name of the event which the code is handling. The following code dispatches the event (and triggers server-side code invocation):

// dispatching the event from a Java app
Backendless.Events.dispatch( "foo", null );

You can dispatch the event in the same manner from all other client types. For the information on the API and the process of developing custom event handlers, see Custom Events in Backendless documentation.

Leave a Reply