I have an Orx event handler callback as a static member function of a C++ class. I want that callback function to be able to access an instance of the class.
Right now I store a pointer to the class instance in a global so the callback can use it. Is there a way to get rid of the global, like sending an extra parameter to the callback function?
Comments
Do you have only one instance of your class or many ?
If you have only one, the good solution (for me) is to use a Singleton Pattern (it's just a static method that return the only one instance of a class, and this class need a private constructor). There's some example of that is Scroll, if you use it (search for GetInstance() methods).
If I'm correct, you can pass an extra parameter when you send a event (payload), but I think it's not what you want because the sender of the event doesn't care about handlers, and your instance is specific to only one handler.
So, Singleton solution if you only have one instance
I can imagine the situation would arise where I have to do this with more than once instance of a class, though. What would be the solution in that case?
By supposing you want to access many instances from your handler, I think a Singleton on top of them could do the tricks. Usually, in my case, I use Singleton for "manager" object and I asj him for other data if needed.
In that case, in your handler, you can retreive the manager using the GetInstance() methods, and just add some methods in your manager to retreive your instances.
No ?
Hope that help !
Now if you have more than one class instance, it all depends on how the event is linked to it, isn't it? If it's an object instance class, you probably stored it with orxObject_SetUserData() and can probably get the concerned object from the event parameters.
It's really on a per case basis but so far I only had to deal with "managers" via singletons or via instances linked somehow via the UserData pointer stored in the orxOBJECT.
Do you have a more concrete example?
You're right, though.. sending the instance pointer in the orxOBJECT UserData would work just fine in that scenario.
And for you own custom events, you can of course stuff anything you want in the payload.
Then a GameObject class
and derived from the GameObject are my objects.
All these object classes (e.g. Player) are put into the orx objects as SetUserData pointers.
The GameObject class has functions I need such as
- Update
and
- Collision
(Just using these 2 right now)
On an event I just send them through to the userdata of the object in question.
On 'update' I send every object with userdata the Update command.
BTW, take a look at Scroll! My tutorials on setup are on the wiki. It makes it very convenient to implement event handler callbacks for game objects.