Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle class event with regular procedure (Delphi)

I am programmatically creating a database connection object inside a simple procedure (not a method in a class).

mydb:= TUniConnection.Create(nil);
mydb.Database:= knowledge_db_name;
mydb.LoginPrompt:= False;
mydb.Username:= aaa;
mydb.Password:= bbb;

now I need to handle errors and disconnections with other procedures. When I try to do:

mydb.OnError:= OnConnectionError;
mydb.OnConnectionLost:= OnConnectionLost;

The compiler tells me

[DCC Error] test.pas(373): E2009 Incompatible types: 'method pointer and regular procedure'

How can I work around this? Here are the definitions of the event procedures:

procedure OnConnectionError(Sender: TObject; E: EDAError; var Fail: Boolean);
procedure OnConnectionLost(Sender: TObject; Component: TComponent; ConnLostCause: TConnLostCause; var RetryMode: TRetryMode);
like image 951
Miguel E Avatar asked Jun 18 '12 12:06

Miguel E


1 Answers

If you don't have a suitable class to put the event handlers in you can define a dummy class and make the event handlers class procedures. Then you don't have to create an instance of the class but can assign mydb.OnError:= TMyDummyEventHandlerClass.OnConnectionError;.

Here is an example - I use different events because I don't have TUniConnection but want to be sure everything compiles. :-)

type
  // Dummy class to hold event handlers:
  TXMLEventHandlers = class
    // Event handlers:
    class procedure OnBeforeOpen(Sender: TObject);
    class procedure OnAfterOpen(Sender: TObject);
  end;

class procedure TXMLEventHandlers.OnBeforeOpen(Sender: TObject);
begin
  MessageBox(0, PChar(ClassName + '.OnBeforeOpen'), nil, 0)
end;

class procedure TXMLEventHandlers.OnAfterOpen(Sender: TObject);
begin
  MessageBox(0, PChar(ClassName + '.OnAfterOpen'), nil, 0)
end;

procedure Test;
var
  xml: TXMLDocument;
begin
  xml := TXMLDocument.Create(nil);
  try
    // Note: No instance of `TXMLEventHandlers` must be created:
    xml.AfterOpen := TXMLEventHandlers.OnAfterOpen;
    xml.BeforeOpen := TXMLEventHandlers.OnBeforeOpen;

    xml.Active := True; // Calls the two event handlers
  finally
    xml.Free;
  end;
end;
like image 81
Uli Gerhardt Avatar answered Oct 05 '22 13:10

Uli Gerhardt