Cocos2D-x游戏开发之:CCNotificationCenter观察者模式基础

Cocos2D-X为我们准备了太多东西,当我们想要监听一个动作但是都不能老是盯在这一件事情上的时候就可以用他为我们量身定制的观察者模式,今天我们初步来学习一下这个传说很久的观察这模式在Cocos2D-X中的简单运用。

其实观察者模式的初步学习还是很简单的我们只要定义两个函数即可:

[cpp]  view plain  copy
  1. class HelloWorld : public cocos2d::CCLayer  
  2. {  
  3. public:  
  4.     virtual bool init();    
  5.     static cocos2d::CCScene* scene();  
  6.     void  sengMsg(CCObject *pSender);  
  7.     void testMSG(CCObject *pSender);  
  8.     CREATE_FUNC(HelloWorld);  
  9. };  
  10.   
  11. #endif  // __HELLOWORLD_SCENE_H__  

然后在init()函数中添加事件的监听。在SendMSG()函数中发送事件消息。

[cpp]  view plain  copy
  1. bool HelloWorld::init()  
  2. {  
  3.     bool bRet = false;  
  4.     do   
  5.     {  
  6.         //  
  7.         // super init first  
  8.         //  
  9.   
  10.         CC_BREAK_IF(! CCLayer::init());  
  11.         CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(HelloWorld::testMSG),"test",NULL);  
  12.         CCMenuItemLabel *labelItem = CCMenuItemLabel::create(CCLabelTTF::create("Send MSG","Arial",26),this,menu_selector(HelloWorld::sengMsg));  
  13.         CCMenu *menu = CCMenu::create(labelItem,NULL);  
  14.         this->addChild(menu);  
  15.         bRet = true;  
  16.     } while (0);  
  17.   
  18.     return bRet;  
  19. }  
  20. void HelloWorld::sengMsg(CCObject *pSender)  
  21. {  
  22.     CCLOG("sendMSG");  
  23.     CCNotificationCenter::sharedNotificationCenter()->postNotification("test",NULL);  
  24. }  
  25. void HelloWorld::testMSG(CCObject *pSender)  
  26. {  
  27.     CCLOG("testMSG");  
  28. }  

现在当我们点击菜单按钮式就可以看到事件被发送和接受的调试信息:



0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值