Raising Events

Your objects can raise events just like a control, and the code using the object can receive these events by using the WithEvents and Handles keywords. Before you can raise an event from your object, however, you need to declare the event within the class by using the Event keyword.

In the Person class, for instance, you may want to raise an event anytime the Walk method is called. If you call this event Walked, you can add the following declaration to the Person class:

Public Class Person

Private msName As String Private mBirthDate As Date Private mTotalDistance As Integer Private mPhones As New Hashtable() Private mAllergens As Integer Public Event Walked()

Code snippet from Person

Events can also have parameters, values that are provided to the code receiving the event. A typical button's Click event receives two parameters, for instance. In the Walked method, perhaps you want to also indicate the distance that was walked. You can do this by changing the event declaration:

Public Event Walked(ByVal distance As Integer)

Now that the event is declared, you can raise that event within the code where appropriate. In this case, you'll raise it within the Walk method, so anytime a Person object is instructed to walk, it fires an event indicating the distance walked. Make the following change to the Walk method:

Public Sub Walk(ByVal distance As Integer) mTotalDistance += distance RaiseEvent Walked(distance) End Sub

Code snippet from Person

The RaiseEvent keyword is used to raise the actual event. Because the event requires a parameter, that value is passed within parentheses and is delivered to any recipient that handles the event.

In fact, the RaiseEvent statement causes the event to be delivered to all code that has the object declared using the WithEvents keyword with a Handles clause for this event, or any code that has used the AddHandler method. The AddHandler method is discussed shortly.

If more than one method will be receiving the event, then the event is delivered to each recipient one at a time. By default, the order of delivery is not defined — meaning you can't predict the order in which the recipients receive the event — but the event is delivered to all handlers. Note that this is a serial, synchronous process. The event is delivered to one handler at a time, and it is not delivered to the next handler until the current handler is complete. Once you call the RaiseEvent method, the event is delivered to all listeners one after another until it is complete; there is no way for you to intervene and stop the process in the middle.

0 0

Post a comment