cocos2d-x NotificationCenter

时间:2021-11-08 21:00:47

转自:http://www.xinze.me/cocos2d-x-ccnotificationcenter/

在前端开发中,JS和as3中都有很好的监听机制, 我们使用Event的addEventListener、dispatchEvent即可实现松耦合。 在尝试使用cocos2d-x的时候,我寻找这种事件机制。

由于自己是不愿去再去写一些一定存在的代码, 就想去找网上找了, 第一想法,就是立马去看PureMvc – c++,这儿的观察者模式可以轻易实现松耦合,但是看了看,感觉在c++中使用有些麻烦,就放弃了。 在google中搜索,找到如何一篇文章: Generic Observer Pattern and Events in C++ – CodeProject 看了后,觉得可以使使用这个思路去做了。

无意中问了下朋友得知,cocos2d-x中是有 CCNotificationCenter 可以使用的,测试了下效果, 很方便,使用方式如下:

//发送事件
CCNotificationCenter::sharedNotificationCenter()->postNotification(CLICK_TEST_MSG, (CCObject*)data); //监听事件
void GameManager::initListener()
{
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(GameManager::onClickTest), CLICK_TEST_MSG, NULL);
} //处理事件
void GameManager::onClickTest(CCObject* obj)
{
CCMessageBox("onClickTest", "Title"); //移除监听事件
CCNotificationCenter::sharedNotificationCenter()->removeObserver(this, CLICK_TEST_MSG);
}