What are Events in OO ABAP?
Events allow objects to publish status or some information about itself. Other object can respond to that change using this.
Event thus serve as an action items using which object of different types can interact with each other on specific occasions/ actions.
What are different types of Event?
There are two types of events
1. Static: Static events can be raised without need of creating object instance and can be raised stand alone without any instance. Static instance could be raised only from Static method.
2. Instance Dependent: Instance dependent events are always specific to an object instance. Therefore they need an object instance to raise them.
How to trigger Events?
Events in SAP follow a typical “Broadcast” scenario similar to a news station.
“An Entity publishes events in its newsletter for everyone and anyone who wants to read it then needs to subscribe for a copy of that newsletter.”
Similarly, Event are published in the class definition and different objects then subscribe to those events depending on needs.
For e.g. Class CL_GUI_ALV_GRID for ALV Grid has published event like USER_COMMAND, DOUBLE_CLICK and ONDRAG etc which could be used by other objects (programs to subscribe and use).
Any method of class can raise its events.
Steps Followed in Event Mechanism
1. Define Event: Event would be defined at the time of class declaration. When using standard SAP class, this is need not required generally. However for custom classes you can define events.
2. Raise Event: Events can be raised by any method of class. This is to be done using ABAP statement
Method EventRaisingMethod. RAISE event. ENDMETHOD.
3. Define Handler Class: Handler class is the one which is responsible for taking action on the events subscribed by other object. It could include events of different object types (classes). Handler class can group handler methods of different events from one/ many classes
CLASS handler_class DEFINITION. PUBLIC SECTION. METHODS: handler_method FOR EVENT raised_event OF raising_class. ENDCLASS.
4. Define Handler Method: Handler Methods are the one which describe the action to be performed when the event is raised.
CLASS handler_class IMPLEMENTATION. METHOD handler_method. "… some logics here ENDMETHOD. ENDCLASS.
5. Register Event Handler: This would mean subscribing to the event of a particular class.
SET HANDLER handler_instance-handler_method FOR ALL INSTANCES. SET HANDLER handler_instance-handler_method FOR handled_instance.
How events works in SAP?
When an event is fired then the event handlers that have registered themselves with SET HANDLER statement are executed by runtime.
The 5 steps are implemented uniformly across different usages of Object oriented programming in sap. The best example could be CL_GUI_ALV_GRID and its associated events which are commonly used.