Search code examples
cocos2d-xcocos2d-x-3.0

How to create an custom event listener without a lambda function in Cocos2d-x 3.x?


The new Event Dispatcher in Cocos2d-x 3.x has several test examples that show lambdas being used for the callbacks in the same class. I have a base class that needs to register for an event, then have an overidden subclass method respond to that event. How would I accomplish this?

In my base class:

EventListenerCustom* listener = EventListenerCustom::create("my_event", myVirtualEventMethod);

Updated based on Kazuki's answer:

class BaseScene : public cocos2d::Layer
{
    public:
    virtual void myVirtualEventMethod();
};

My method:

EventListenerCustom* listener = EventListenerCustom::create("my_event", CC_CALLBACK_1(BaseScene::myVirtualEventMethod, this));

See the error in comments below.


Solution

  • EventListenerCustom::create() accepts std::function.

    https://github.com/cocos2d/cocos2d-x/blob/v3/cocos/base/CCEventListenerCustom.h#L59

    static EventListenerCustom* create(const std::string& eventName, const std::function<void(EventCustom*)>& callback)
    

    So you can specify a member function with std::bind like this.

    EventListenerCustom* listener = EventListenerCustom::create("my_event",
        std::bind(&YourSubclass::myVirtualEventMethod, this, std::placeholders::_1));
    

    And there is a macro for it in cocos2d-x.

    EventListenerCustom* listener = EventListenerCustom::create("my_event",
        CC_CALLBACK_1(YourSubclass::myVirtualEventMethod, this));
    

    EDITED

    No viable conversion from '__bind<void (BaseScene::*)(), BaseScene ,
        std::__1::placeholders::__ph<1>&>' to 'const std::function<void(Eventcustom)>'
    

    Because the type of myVirtualEventMethod is not the same as void(EventCustom*). Thus it should be

    virtual void myVirtualEventMethod(EventCustom*);
    

    Or

    EventListenerCustom* listener = EventListenerCustom::create("my_event",
        CC_CALLBACK_0(YourSubclass::myVirtualEventMethod, this));