Delegates?

Hi all, easy one for you maybe, but I’ve not used delegates before and feel I may have a need for them now. Confused thus far!

I want to be able to call a method on various windows from a container. This container will be located on multiple windows - currently I do a lot of “case window isa” to determine which window the container is sat on and call the appropriate method that way. I’m sure there’s an easier way using delegates, could someone point a poor lost soul in the right direction?

Thanks in advance,
Dave.

From what I can understand about your use case, an Event Definition might be a more simple approach. Each window’s instance of the container can have its own Event Handlers.

2 Likes

Many thanks Tim, this will work great.

You are going to create a lot of inter dependencies in going down that road, you would be better to use come kind of publish and subscribe model so you keep the objects as decoupled as possible thus making future maintenance and enhancement easier.

That’s why you use events. To prevent those interdependencies.

1 Like

You can’t win in a conversation involving two Tim :wink:.

1 Like

This is the first time I read this (publish and subscribe), can you point me to more information or an example to understand what is that?

1 Like
1 Like
  1. Make a module called Messaging
  2. Add an Interface named Receiver with a single method:

Message(name as string, data as variant)

  1. Add a private property: receivers() as Receiver
  2. Add protected methods Register and Unregister with the parameter (obj as Messaging.Receiver) which add/remove obj from the receivers array.
  3. Add a protected method Send(name as String, data as variant = nil) which loops over the receivers and calls the Message method with the same parameters. You may want to use a timer for this.

Now… each thing that wants to receive messages must have the Receiver interface applied to it and when they open, you call register and when they are destroyed, you call unregister. When you need to send a message, you call

Messaging.Send(name, data)

To avoid memory leaks, you could make the receivers array use WeakRefs and just throw away/skip the ones that become nil.

Be very careful not to create messaging circles where one message creates another that loops back on itself.

1 Like

Hmmm. I must look into this to see if I can use this technique.

Monty Python - Tim 2 - Holy Grail

2 Likes

One time many years ago the local theatre group had five Tims. There was also an Aussie so I did wonder about doing the Monty Python Bruces sketch but, y’know, in reverse.

1 Like