2007. május 24., csütörtök

Using One Event for many Components


Problem/Question/Abstract:

Using One Event for many Components

Answer:

This tip is a pretty basic one, but if you haven't come across it, using it can make your coding a lot easier and more efficient.

Delphi allows one coded event to be assigned to many event handlers as long as the methods are of the same type - ie., they have the same arguments.  The classic example is the OnClick event which is shared by many components.  This can be done in code in the following way.

procedure ClickMyComponent(Sender: Tobject);
begin
  //Some code goes here
  ShowMessage('This is my Onclick handler');
end;

{You can then assign this procedure to as many event handlers as you wish.}

procedure AssignEvents;
begin
  MyButton.OnClick := ClickMyComponent;
  MyLabel.OnClick := ClickMyComponent;
  MyCombo.Onclick := ClickMyComponent;
  // You Get the message!
end;

Each time one of these components is clicked, the above procedure 'ClickMyComponent' is executed.  This can be useful is certain circumstances, but mainly in this tip it serves to illustrate my main point  - reduce designtime coding by assigning events.

Assigning at designtime.

In the object inspector you may have noticed that the right hand side of the events tab is a combo box.  This allows you to choose to assign an already written event handler to the current components event (only event handlers of the right type are shown in the combo box).  This is the design time way of doing the above code.

At a glance it can seem like a nice but essentially useless ability to have.  How often are you likely to have two buttons, or a button and a label that share the same onclick code.  This may be true but it does happen.  Also an area where you do have many controls sharing code is in respect to Main Menus, Popup Menus and Speedbuttons.

eg.,

You want to let the user of your application be able to set the view type of a TlistView component at run time so you assign the four values to a View Menu  on your main menu and you right the necessary code in each event handler of each menu item.  Later on you decide to add speedbuttons, and a popupmenu in the listview to do the same thing.

Do you rewrite all the code?  Redo all the work you have done (even if you cut and paste)?

No you assign each new speedbutton and popupmenu item in its onclick handler in the objectInspector the handler for the corresponding mainmenu item.

Voila, you've managed to save yourself a lot of hassle and time and made your code more efficient (although possibly slightly harder to follow - so comment well).

Hope this is of use.

Nincsenek megjegyzések:

Megjegyzés küldése