Manual Event Binding
So let's assume we have the following method as a member of our form, and would like to bind it to a button on our form:
We could do so by using the new BindEvent()
function. We could use that function whenever and wherever we want. In this example, the form's Init()
method might be the best place:
The first two parameters define the source of the event (object, plus name of the event), the second pair defines the handling object and the method we want to delegate the event to.
If you run this code inside a form and click the button, you will see the message box firing. Note that this doesn't influence the original click event at all. You can check this by simply adding another message box to the button's Click()
method. In that case, the ShowMessage()
method will fire first (whenever a Click
event is raised), and then the Click()
method will follow.
If you would like the sequence to occur the other way around, with Click()
firing first, you can indicate so by passing an optional 5th parameter to the BindEvent()
Aside from the sequencing, what is interesting here is that we can have more than one handler for an event. In this case, we have our ShowMessage()
method as well as the default Click()
method. And it doesn't stop there! In fact, we can add as many different event handlers to each event as we want!
Just like we bound event handlers to events, we can also unbind events. So let's assume we want our ShowMethod()
to only handle the very first Click
event the button raises, but not subsequent ones. In that case, we could add the following code to the ShowMessage()
Of course, this assumes that the ShowMessage()
method is designed to be attached to THIS.command1
, and no other object. In real-life scenarios, you may not want to do that, because these types of dynamic event handlers generally are very generic so they can be attached to different objects. However, it would be easy enough to put this code in other methods or event handlers as well. We will also explore some generic ways to discover current bindings a later in this article.
Note that there also is a simpler version of UnbindEvents()
that receives one parameter (an object reference):
This will automatically unbind all event handlers on the THIS
-object (which would include our ShowMessage()
method). In addition (and this is important to know), it will also unbind all event handlers in other objects, that are binding to events that may occur on the THIS
-object. Therefore, if another object binds to the Activate
event of the form (for instance), that binding will be released as well. While this is useful in some scenarios (perhaps we want to release the THIS
-object from memory), it is also a rather barbaric approach, compared to the surgical accuracy of the 4-parameter version.