Custom Events

Top  Previous  Next

In addition to the built-in events triggered by the API calls, Backendless supports custom, developer-defined events. A custom event also has an event handler which is a block of custom business logic. 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. Custom business logic which handles the event may also return a value which is delivered back to the client-side that dispatched the event.


For example, consider the following custom event handler:

Backendless.ServerCode.customEvent('foo', function(req) {
  // event handling logic is here.

The code above is an custom event handler for the "foo" event. The event name is declared using the Backendless.ServerCode.customEvent function. Event arguments are delivered to the code via req.args argument.


Custom Event Return Value

The return value of the custom event method is sent to the client application where the event was dispatched. For example, the following code returns a JavaScript 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.

/* global Backendless */

Backendless.ServerCode.customEvent('foo', function(req) {
    console.log( "event arguments: " + req.args );
    return {status:"Event Processed"} ;


Development and Deployment

Developing and deploying a custom event handler follows the same development process as for API Events handlers and timers.


Code Generation

Backendless Console includes a special section for custom events. The code generator makes it very easy to create the required code which can be used to develop a custom event handler:



To create a custom event handler using the console:

1.Login to console and select an application.
2.Click the Business Logic icon.
3.Select Custom Events in the Service Events Handlers section.
4.Click the Add Event Handler button and enter a name for the event.
5.Console generates the code which can be seen in the file /app/handlers/custom-events/eventname.js. For example, in the image above, the file name is foo.js, since the event name is "foo".
6.Download the generated code using the Download Code button.
7.Add your own custom business logic into the generated method.
8.Proceed with debugging and deployment to production as described in the documentation.


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.


Available implementations:










Methods are accessible via the Backendless.Events accessor. See the example below.


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
  public Map handleEvent( RunnerContext context, Map eventArgs )
    // add your code here
    return Collections.emptyMap();


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

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

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


All methods are available via accessor. Method signatures:

// synchronous method:
-(NSDictionary *)dispatch:(NSString *)name args:(NSDictionary *)eventArgs fault:(Fault **)fault;
// async method with responder
-(void)dispatch:(NSString *)name args:(NSDictionary *)eventArgs responder:(id <IResponder>)responder;
// async method with block-based callbacks
-(void)dispatch:(NSString *)name args:(NSDictionary *)eventArgs response:(void(^)(NSDictionary *data))responseBlock error:(void(^)(Fault *fault))errorBlock;


Method signature:

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


var eventArg = {weather:"sunny"};
var successHandler = function( response ) {
var errorHandler = function( response ) {
Backendless.Events.dispatch( "foo", eventArgs, new Backendless.Async( successHandler, errorHandler ) );


There is only one asynchronous method for dispatching a custom event:

Backendless.Events.dispatch( eventName:String, eventArgs:Object, responder:IResponder ): AsyncToken;


var eventArgs:Object = {weather:"sunny"};
Backendless.Events.dispatch( "foo", eventArgs, new Responder(
                           function( evt:ResultEvent ):void
                             trace( evt.result );
                          function( evt:FaultEvent ):void
                             trace( evt.fault.faultDetail );


Method signatures:

// synchronous method
public IDictionary Backendless.Events.Dispatch( String eventName, IDictionary eventArgs );
// asynchronous method
public void Backendless.Events.Dispatch( String eventName, IDictionary eventArgs, AsyncCallback<IDictionary> callback )


Dictionary<String, String> eventArgs = new Dictionary<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 );




URL:<app version>/servercode/events/<event name>


<app version>        - name of the backend version (Backendless assigns "v1" by default to all new apps)

<event name>        - name of the event to dispatch


Request headers:

application-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. This header is mandatory. Please refer to the Setup section for information on how to obtain the values for the header.
secret-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. This header is mandatory. Please refer to the Setup section for information on how to obtain the values for the header.
Content-Type- the static value, should be set to application/json. This header is mandatory.
application-type- the static value, should be set to REST. This header is mandatory.


Request body:

an arbitrary JSON object which will be transformed to java.util.Map when the event is delivered to the event handler.



-H application-id:application-id
-H secret-key:secret-key
-H application-type:REST
-H Content-Type:application/json
-d '{"weather":"sunny"}'


Method signatures:

public function Backendless::$Events->dispatch( $event_name, $event_args_array );



Backendless::$Events->dispatch( "foo", ["weather" => "sunny"] );

Please let us know how we can improve the documentation by leaving a comment. All technical questions should be posted to the Backendless Support forum. We do not respond to the technical questions on the documentation pages.: