Event RTTI Invocation (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example shows how to use the RTTI of an event to invoke it. Two classes are defined: TMapModel (event producer) and TMapView (event consumer). TMapModel has a specific event: OnChange (of type TMapModelChangeEvent). Procedure InvokeOnChangeEvent retrieves the RTTI available for this event and invokes it.

Code

program Program1;

{$APPTYPE CONSOLE}

uses SysUtils, Rtti;

type
  TMapModelChangeEvent = procedure(Sender: TObject; Area: Pointer) of object;

  TMapModel = class
  private
    FOnModelMapChange: TMapModelChangeEvent;
  public
    property OnChange: TMapModelChangeEvent read FOnModelMapChange
      write FOnModelMapChange;
  end;

  TMapView = class
  public
    procedure Update(Sender: TObject; Area: Pointer);
  end;

procedure TMapView.Update(Sender: TObject; Area: Pointer);
begin
  Writeln('Map view update');
  // Use the area information...
end;

procedure InvokeOnChangeEvent(mapModel: TObject);
var
  context: TRttiContext;
  method: TValue; // System.TMethod
  methodType: TRttiInvokableType;
begin
  { Get the value of the OnChange property, which is a method pointer }
  method := context.GetType(mapModel.ClassType).GetProperty('OnChange')
    .GetValue(mapModel);

  { Display the method code and data pair }
  Writeln(method.ToString);

  { Get event RTTI }
  methodType := context.GetType(method.TypeInfo) as TRttiInvokableType;
  Writeln(methodType.Name);

  { Invoke event }
  { The first parameter must be the procedure/method pointer in a TValue variable }
  methodType.Invoke(method, [mapModel { Sender } , nil { Area } ]);
end;

var
  mapModel: TMapModel;
  mapView: TMapView;

begin
  mapModel := TMapModel.Create;
  mapView := TMapView.Create;

  try
    mapModel.OnChange := mapView.Update;
    InvokeOnChangeEvent(mapModel);
  finally
    mapModel.Free;
    mapView.Free;
  end;

end.

Sample Console Output

(method code=00495334, data=00D2A6E0)
TMapModelChangeEvent
Map view update

Uses

Personal tools
Assistance