Cocos2d-x 的自定义事件监听机制

作者 qiuzhong 日期 2016-02-15
Cocos2d-x 的自定义事件监听机制

EventListenerCustom的使用

最近发现可以通过cocos2d-x的事件驱动机制来控制UI,而不是所有的UI都需要在update中完成
EventListenerCustom只会在触发的时候执行一次UI线程,比起一直在update中等待会节省很多资源
EventListenerCustom在使用的时候后需要先注册

 _listener2 = EventListenerCustom::create("game_custom_event2", [=](EventCustom* event){
std::string str("Custom event 2 received, ");
char* buf = static_cast<char*>(event->getUserData());
str += buf;
str += " times";
statusLabel2->setString(str.c_str());
});
_eventDispatcher->addEventListenerWithFixedPriority(_listener2, 1);

触发事件的代码如下实例

 static int count = 0;
++count;
char* buf = new char[10];
sprintf(buf, "%d", count);
EventCustom event("game_custom_event2");
event.setUserData(buf);
_eventDispatcher->dispatchEvent(&event);

在使用完后需要进行销毁 _eventDispatcher->removeEventListener(_listener)这个方法最好在onExit()中调用