For instance, say I have a class called Body that represents a rigid body. If I instruct that body to sleep (through a method call to an instance of Body) I’d like to be able to raise an event called sleepStart() that a user of the engine could subscribe to or be alerted to so they can respond appropriately in their game.
What sort of paradigm should I be looking at to do this in Xojo. I know you can have custom event handlers in classes butI think they are only called either by subclassing (e.g subclassing the Body class) or by dragging an instance of the class onto a window (not something I’m looking to do as I want to be able to dynamically create new rigid bodies via code).
Is there some sort of event listener paradigm??
This is very easy in Xojo.
In the class Body, add an Event Definition called sleepStart, with no parameters.
When you need to raise that event from with Body, use the following line:
Should have also said, to add the Event Definition, right click on the Body class in the navigator and select Add > Event Definition from the popup menu (I think that’s right, but I’m at work right now and cannot check, but it will point you in the right direction)
and no, you don’t have to drag them on your window. You can keep them as a property of the window and tweak their events with
AddHandler myBody.sleepStart, addressOf SleepStart
where SleepStart is a method of your window that takes an object of Kind Body as Input parameter.
Dont forget to remove the handlers in the close event of the window to avoid memory leaks!
(For dynamically created objects of type body, the same applies. You need to keep them alive by adding them to a property of your window anyhow. like an array of body or a dictionary. You can add the handlers when you add them to this property and remove them while you are removing them from it.)