Mega Code Archive

 
Categories / Delphi / Functions
 

How to write a callback function

Title: How to write a callback function Question: How can you split code from the user-interface from other code - for example the 'business rules' ? Answer: The function CopyAllFiles copys files from A to B. This process could take longer, therefore a feedback to the user-interface is necessary. We don't want to just implement this - the aim is to write a code that is independent from the user-interface and can be used in many application areas. To achieve this we need a procedure-parameter - this you can call callback. We just have to define a type of a procedure - in this example TProcessEvent - than we can define a parameter from this type in the function CopyAllFiles: type TProcessEvent = procedure(aAmount, aCurrent: integer; aFilename: string; var aCancel: boolean); This is how we create an exit from our function that can start a procedure in the main program. procedure CopyAllFiles(aPathPlusMask: string; aSubFolders: boolean; aDestPath: string; aOverwrite: boolean; aProcessEvent: TProcessEvent); begin ... // a lot of cpu-cicles needed - propobly in a loop if Assigned(aProcessEvent) then aProcessEvent(...); ... end; In the main program the 'event-handles' or the 'callback-function' can be defined with the same parameterlist than the type TProcessEvent is forcing it: procedure ProcessProc(aAmount, aCurrent: integer; aFilename: string; var aCancel: boolean); begin // User-Interface Code end; This function can than be passed to CopyAllFiles: CopyAllFiles('*.*',false, 'c:\temp', true, ProcessProc);