I'm using Delphi 11. Is there a way to run a specific function inside a TDataModule, but only if this datamodule exists on my project ?
I need a way to check if the datamodule exists and call the function as string, because some projects will have this datamodule added, others not.
Instead of this :
myDataModule.myfunction(param);
Would be something like this imaginary code :
if TDataModule(findcomponent('myDataModule')) <> nil then
TDataModule(findcomponent('myDataModule')).call('myfunction','param');
CodePudding user response:
A lightweight solution could be Messages (those from System.Messaging).
- Declare a new TMessage descendant holding the parameters needed for the call
- When the datamodule is created it Subscribes to this message type with a handler doing the actions.
- Instead of searching for the datamodule just Send the message.
CodePudding user response:
This may or may not be applicable to your situation... But that seems like the kind of situation I would solve with a multicast event.
Your code would call Event.Execute('Param')
instead of myDataModule.myfunction(param)
.
The part of your code responsible for "importing" and creating the datamodule would register to the event. Something like :
EventClient := TEventClient.create(
procedure (const AParam : ParamType)
begin
myDataModule.myfunction(AParam)
end);
EventClient.Observe(Event);
Now, this approach makes sense if the reasons to call your function is "event-like", but this might make less sense in other contexts.
As for library implementing multicast event, I can't recommend any as I always used a proprietary one. If you need inspiration to implement your own, you can look at TMultiCaster in unit Vcl.AppEvnts which implements more or less the same concept.