user3428422
user3428422

Reputation: 4560

VB - Raising events from another class correctly

I know there is a lot of information regarding the above, but I do not grasp how to do this correctly, so I thought using a real life problem may help to click it for me and others.

So in class A I have defined an event method

Public Sub textChangedMethod(ByVal textedChanged As Boolean)
  ' do some code on properties of this class only
End Sub

What I need to happen is I need some other class to raise this method,

I have a concept but its totally wrong.

At the moment I pass an instance of class A to the another class so it can reference the event (this must be wrong)

Dim UI As New newClassDialog(Me) 'class A

In this new class I have the event handler

Public Event textChanged(ByVal textedChanged As Boolean)

So in the constructor of the new class I can now add the handler

Public Sub New(ByRef classA As Class A)

   ' This call is required by the designer.
   InitializeComponent()

   AddHandler textChanged, AddressOf classA.textChangedMethod

End Sub

Now of course I can raise the event like so

RaiseEvent textChanged(True)

Basically passing in the class seems ridiculous in my eyes, so using this example is there a 'proper' way of doing this?

Thanks

Upvotes: 0

Views: 2593

Answers (1)

Steve
Steve

Reputation: 216293

It seems that you are inverting the roles. In this context the class that raises the event shouldn't know who handles the event. It is the responsability of class that instantiate the newClassDialog to add the event handler for the events raised by the called class

Dim UI As New newClassDialog(Me) 
AddHandler UI.textchanged, AddressOf Me.textChangedMethod

Upvotes: 1

Related Questions