ReDefining an event handler on the fly

Hey gang,

I am creating a class that will handle some I/O for various types of controls. To start out with, I’m using Serial or TCP sockets.

I’m trying to make this truly generic but have a question about how to restructure some events.

Serials and TCP Sockets have a DataAvailable event. In my code the DataAvailable event may be implemented in the UI or it may be implemented via an AddHandler directive. The thing is - when it gets to this new class - I don’t want to know where the DataAvailable event is implemented. I just want to temporarily implement it with a method in my class. Then when the operation of the class is done, I want to return the DataAvailable event handler to where it was previously.

Is there a way to do this? I can’t use AddHandler to add a new handler because you have to use RemoveHandler first and I don’t necessarily know the Handler’s method name or location.

I just want to temporarily substitute one method for another. It sounds like a good use of a Delegate, but I’ve never directly used Delegates before (with the exception of AddHanlder), and I don’t know if trying to use a Delegate will interfere with AddHandler or what.

So pointers are appreciated.

  1. Make a Boolean property on your class that indicates whether you want to run your code or the users code.
  2. Make a new event handler for DataAvailable, cloning it’s signature.
  3. Make a method which contains your override code.
  4. In DataAvailable, use the Boolean to Raise the event or call your own method.

I’m still not sure I understand.

I have a TCPSocket, I’m passing into my class as a type of an interface that I have defined.

So I have this type of Interface X. It has a DataAvailable event handler somewhere else in the code - where - I don’t know.

I don’t understand how your steps would allow me to remove the DataAvailable handler from my socket and allow me to process it in the class…

Your new class cant call the passed in objects data available event directly anyways
So its more up to the socket / serial you passed in to expose that to this class than it is for the class to override the event handler arbitrarily

Sounds like what you really should have is the TCP / Socket having a class instance that it delegates ALL event handling to.
If the instance is nil then the TCP / Serial class handles it internally.
If not then it calls the class that is designated as the handler.

So you need an interface for “DataHandler” or whatever and it has methods that the serial / tcp calls if the class is set on the serial / tcp
And a pair of methods for “SetDataHandler / RemoveDataHandler”