Calling the Event

From RAD Studio
Jump to: navigation, search

Go Up to Defining Your Own Events

In your components, you may need to trigger the same event from different parts in your code. You should centralize these calls to an event. That is, create a virtual method in your component that calls the application's event handler (if there is one assigned) and provides any default handling.

These virtual methods are called event dispatchers or Do methods. This is because the most spread naming convention is to name these methods after the event that they trigger, replacing the On prefix with a Do. For example, the convention for the event dispatcher that triggers the OnClick event would be to name it DoClick.

Putting all the event calls in one place ensures that someone deriving a new component from yours can customize event handling by overriding a single method, rather than searching through your code for places where you call the event.

Considerations When Calling The Event

There are two other considerations when calling the event:

Example of an Event Dispatcher

The following is the most simple example of an event dispatcher that follows the considerations listed above:


virtual void __fastcall TComponentName::DoEventName(UnicodeString Parameter1, UnicodeString Parameter2)
  if (FOnEventName)
    FOnEventName(this, Parameter1, Parameter2);


procedure TComponentName.DoEventName(Parameter1, Parameter2: string);
  if Assigned(FOnEventName) then
    FOnEventName(Self, Parameter1, Parameter2);

Using an event dispatcher lets you reduce calls to the event handler to one line. You do not need to check if the FOnEventName variable is assigned every time, you simply call the event dispatcher and this procedure takes care of checking the variable.

This approach also allows developers to create a subclass of your component, to easily override the event triggering.

See Also