Cocos2d-x 中 CCNotificationCenter 的使用

来源:互联网 发布:淘宝店推广平台 编辑:程序博客网 时间:2024/05/17 04:01

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 可以使用的,测试了下效果, 很方便,使用方式如下:

01//发送事件
02CCNotificationCenter::sharedNotificationCenter()->postNotification(CLICK_TEST_MSG, (CCObject*)data);
03 
04//监听事件
05void GameManager::initListener()
06{
07    CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(GameManager::onClickTest), CLICK_TEST_MSG, NULL);
08}
09 
10//处理事件
11void GameManager::onClickTest(CCObject* obj)
12{
13    CCMessageBox("onClickTest""Title");
14 
15    //移除监听事件
16    CCNotificationCenter::sharedNotificationCenter()->removeObserver(this, CLICK_TEST_MSG);
17}
原创粉丝点击