Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi VCL for Win32 - multiple event handlers

Tags:

events

delphi

vcl

I'm looking for some code allowing easy asigning many event handlers to a single event of object... I needed it very much for my plugin architecture, so I implemented some replacement for that, however I don't like my solution for that, so I'd like to know what is yours idea/solution/tip ... My solution is just a list with items like eventName: string; proc: TMyEventProc; where TMyEventProc takes two arguments, sender and eventData: pointer. depending on name of the event, eventData points to different record / object.

Unfortunately this requires declaration of many, many records for being passed as argument. The method is also very slow, and requires to implement calling the required "callbacks" while the "real" event gets hit.

like image 627
migajek Avatar asked Sep 08 '09 22:09

migajek


1 Answers

I implemented a solution to this that works in just about any version of Delphi - it was originally implemented in Delphi 7, although I haven't tested it in earlier versions (but if you're using Delphi 7 yourself, then that's all you need to know, right?). :)

iirc this was at least in part the inspiration for Allen Bauer's post. You can see my implementation demonstrated in some videos and download the code from my blog:

The posts you are interested in are tagged "multicast". The download link for the final code is available in this post.

In my approach, you derive a class from TMultiCastEvent. All your derived class has to do is implement some simple type safety protection for adding, removing and invoking an event with a specific signature.

An implementation for TNotifyEvent - procedure(Sender: TObject) - is provided with the implementation both "to get you going" (ime most "useful" multicast events are simple notifications) and also as an example of how to derive multicast event classes for specific event signatures.

Once you have your multicast event class you can use regular "event handlers" interchangeably with the multi-cast version, e.g. given some imaginary button class with a multi-cast On_Click event (I've adopted a convention of interposing an underscore in the event name to identify it as multicast, vs regular "uni-cast" events):

Code that assigns a handler to a unicast click event:

  Button.OnClick := MyClickHandler;

Can directly add that same handler to a multi-cast Notify event:

  MultiCastButton.On_Click.Add(MyClickHandler);

My implementation also includes a number of refinements, such as the ability to disable events and have handlers automatically removed from handlers when the implementing object is destroyed (this involves a small amount of housekeeping which can be ignored if necessary but which can be useful under certain circumstances).

All of which is described and demonstrated in my blog posts.

Enjoy. :)

like image 86
Deltics Avatar answered Sep 20 '22 11:09

Deltics