Skip to content

Custom Events

In addition to the built-in events triggered by the API calls, Backendless supports custom, developer-defined events. A custom event is implemented by an event handler which can be defined using Backendless Console. Custom events can be triggered through a specialized API call from a client library or by other custom business logic. A custom event may accept event arguments and return a value which is delivered back to the client-side that has triggered the event.

Consider the following 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 code above is a custom event handler for the "foo" event. The event name is declared using the @BackendlessEvent annotation. Event arguments are delivered to the code via the eventArgs argument.

Custom Event Return Value

The return value of a custom event handler is sent to the client application where the event was dispatched. For example, the following code returns a Java java.util.HashMap object. Each client type adapts the return value to a data structure in the native environment. For instance, Android/Java client would receive the response as java.util.Map.

import com.backendless.servercode.RunnerContext;
import com.backendless.servercode.annotation.BackendlessEvent;

import java.util.Map;
import java.util.HashMap;

@BackendlessEvent( "foo" )
public class FooEventHandler extends com.backendless.servercode.extension.CustomEventHandler
{
  @Override
  public Map handleEvent( RunnerContext context, Map eventArgs )
  {
    HashMap result = new HashMap();
    result.put( "status", "Event Processed" );
    return result;
  }
}

Create Custom Event Handler in Console

To create a custom event handler using Backendless console:

  1. Login to console and select an application. Click the Business Logic icon.
  2. Click EVENT HANDLERS, then click the New Event Handler link:
    new-event-handler-js.zoom80
  3. Make the selection as shown in the screenshot below and enter CoolEvent for the Event field:custom-event-java-v4
  4. Click SAVE. Backendless generates event handler and places it into the Draft mode. You can see the code for the event handler by downloading the project (see the Download link in the menu) or by switching to the CODING section and navigating to the Java source file with the event code. Notice, the Java code cannot be edited in console, it is provided only as a reference.
  5. Download the code and follow the same steps for developing/debugging/deploying the event handler as in the Quick Start guide.

API for Dispatching Custom Events

All Backendless client SDKs include the functionality for dispatching a custom event. The API allows to send event arguments to the server-side and receive the result from the event handler.

Android/Java

HashMap args = new HashMap();
args.put( "weather", "sunny" );

Backendless.Events.dispatch( "foo", args, new AsyncCallback <Map>()
{
  @Override
  public void handleResponse( Map result )
  {
    System.out.println( "received result " + result );
  }

  @Override
  public void handleFault( BackendlessFault backendlessFault )
  {
    System.out.println( "got error " + backendlessFault.toString() );
  }
});

iOS

All methods are available via the backendless.events accessor. Method signatures:

-(void)dispatch:(NSString *)name args:(NSDictionary *)eventArgs response:(void(^)(NSDictionary *data))responseBlock error:(void(^)(Fault *fault))errorBlock;

JavaScript

Method signature:

Backendless.Events.dispatch( eventName, eventArgs, Async );

Example

var eventArgs = { weather: 'sunny' };   

var successHandler = function( response ) {   
    console.log('result', response)  
};   

var errorHandler = function( error ) {   
   console.log('error:', error)  
};   

Backendless.Events.dispatch( 'foo', eventArgs )   
  .then( successHandler )   
  .catch( errorHandler );

.NET

Method signatures:

// synchronous method  
publicIDictionary Backendless.Events.Dispatch( String eventName, IDictionary eventArgs );  

// asynchronous method  
publicvoid Backendless.Events.Dispatch( String eventName, IDictionary eventArgs, AsyncCallback<IDictionary> callback )

Example

Dictionary<String, String> eventArgs = newDictionary<string, string>();  
eventArgs.Add( "weather", "sunny" );  

AsyncCallback<IDictionary> callback = new AsyncCallback<IDictionary>(  
        result =>  
        {  
          System.Console.WriteLine( "received result - " + result );  
        },  
        fault =>  
        {  
          System.Console.WriteLine( "Error - " + fault );  
        } );  

Backendless.Events.Dispatch( "foo", eventArgs, callback );

REST

Method:

POST

URL:

https://api.backendless.com/<APP ID>/<REST API Key>/servercode/events/<event name>

where:

Argument                Description
<APP ID> the ID of your application generated upon its creation. You can find this header in the Manage > App Settings section of the Backendless Console.
<REST API Key> the key of your application generated upon its creation. You can find this header in the Manage > App Settings section of the Backendless Console.
<event name> name of the event to dispatch

Request headers:

Argument                Description
Content-Type the static value, should be set to application/json. This header is mandatory.

Request body:

a JSON object with arguments for the event handler

Example

curl \  
 -H Content-Type:application/json \  
 -X POST  \  
 -d '{"weather":"sunny"}' \  
 -v \  
 https://api.backendless.com/APP-ID/REST-API-KEY/servercode/events/foo