cocos2dx自定义事件类封装

时间:2023-03-09 07:56:40
cocos2dx自定义事件类封装

GameEvent.h:

 #pragma once
#include "cocos2d.h"
USING_NS_CC; class GameEvent {
public:
//封装派发数据
static void dispatchSet(std::string eventName, void *optionalUserData = nullptr);
static void dispatch(std::string eventName, void *optionalUserData = nullptr);
static void addEventListener(std::string eventName, const std::function<void(EventCustom*)>& callback);
static void removeEventListener(std::string eventName);
};

GameEvent.cpp:

 #include "GameEvent.h"

 void GameEvent::dispatch(std::string eventName, void *optionalUserData) {
Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(eventName, optionalUserData);
} void GameEvent::addEventListener(std::string eventName, const std::function<void(EventCustom*)>& callback) {
Director::getInstance()->getEventDispatcher()->addCustomEventListener(eventName, callback);
} void GameEvent::removeEventListener(std::string eventName) {
Director::getInstance()->getEventDispatcher()->removeCustomEventListeners(eventName);
}