Skip to content

Event Handler Asset

Event handlers triggered by the APIs for data, messaging, file and geolocation services must declare an "asset". Asset is a general term used to identify one of the following:

  • a data table for the Data service APIs.
  • a messaging channel for the Messaging APIs.
  • a file or a directory for the File service APIs.
  • a geocategory for the Geolocation APIs.

Consider the following example, which is an event handler for the Data Service's beforeUpdate API event:

package com.coolapp.events.persistence_service;

import com.backendless.servercode.RunnerContext;
import com.backendless.servercode.annotation.Asset;
import com.backendless.servercode.extension.PersistenceExtender;

import com.coolapp.models.Order;

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

/**
* OrderTableEventHandler handles events for the "Order" table. This is accomplished
* with the @Asset( "Order" ) annotation. 
*/

@Asset( "Order" )
public class OrderTableEventHandler extends PersistenceExtender<Order>
{   
  @Override
  public void beforeUpdate( RunnerContext context, Order order ) throws Exception
  {
    // add your code here
  }

}

Notice the @Asset annotation. It specified the name of the table for which the event handler is registered.. When event handlers are created in Backendless Console, it automatically selects the appropriate asset (table, messaging channel, file/directory, geo category) and puts it into the generated code.

It is possible to create a generic event handler, which would respond to all API events for a given service. For example, the event handler below is triggered when a new object is created in any of the application's tables:

package com.coolapp.events.persistence_service;

import com.backendless.servercode.RunnerContext;
import com.backendless.servercode.annotation.Asset;
import com.backendless.servercode.annotation.Async;
import com.backendless.servercode.extension.PersistenceExtender;

import java.util.HashMap;

/**
* GenericTableEventHandler handles events for all entities. This is accomplished
* with the @Asset( "*" ) annotation.  The asterisk denotes "all entities". 
* The methods in the class correspond to the events selected in Backendless
* Console.
*/

@Asset( "*" )
public class GenericTableEventHandler extends PersistenceExtender<HashMap>
{
  @Override
  public void beforeCreate( RunnerContext context, HashMap hashmap) throws Exception
  {
    // add your code here
  }
}
Notice the @Asset("*") annotation. This indicates that the event handler will be triggered for the beforeCreate events for all tables in the application. To determine the name of the actual table which was targeted in the API, use the context.getEventContext() method. For more information see, the Runtime Context section.