The code of this class is fairly simple, as the setter method saved the new pointer and the Click method calls it before doing the standard processing (that is, calling the OnClick event handler if available):

procedure TButton.SetAnonClick(const Value: TAnonNotif); begi n

FAnonClick := Value; end;

97 An interceptor class is a derived class having the same name as its base class. Having two classes with the same name is possible because the two classes are in different units, so their full name (unitname.classname) is different. Declaring an interceptor class can be handy as you can simply place a Button control on the form and attach extra behavior to it, without having to install a new component in the IDE and replace the controls on your form with the new type. The only trick you have to remember is that if the definition of the interceptor class is in a separate unit (not the form unit as in this simple example), that unit has to be listed in the uses statement after the unit defining the base class.

procedure TButton.Click; begi n if Assigned (FAnonClick) then

FAnonClick (self) inherited; end;

How can you use this new event handler? Basically you can assign an anonymous method to it procedure TFormAnonButton.btnAssignClick(

Sender: TObject); begi n btnlnvoke.AnonClick :=

procedure (Sender: TObject) begi n

ShowMessage ((Sender as TButton).Caption); end;


Now this looks rather pointless, as the same effect could easily be achieved using a standard event handler method. The following, instead, starts making a difference, as the anonymous method captures a reference to the component that assigned the event handler, by referencing the Sender parameter.

This can be done after temporarily assigning it to a local variable, as the Sender parameter of the anonymous method hides the btnKeepRefClick method's Sender parameter:

procedure TFormAnonButton.btnKeepRefClick(

Sender: TObject); var aCompRef: TComponent; begi n aCompRef := Sender as TComponent; btnlnvoke.AnonClick :=

procedure (Sender: TObject) begi n

ShowMessage ((Sender as TButton).Caption + ' assigned by ' + aCompRef.Name);

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment