刚才我们 学习了基本的CCNotificationCenter观察者模式在一个层之中监听事件,现在我们再进一步学习如何在不同层之间监听吧,这一节的知识点我们在HelloWorld中发送一个事件消息在OtherLayer中接受并且处理消息。其实很简单只是一个函数换了个位置而已,直接上代码吧:
class HelloWorld : public cocos2d::CCLayer
{
public:
virtual bool init();
static cocos2d::CCScene* scene();
void sengMsg(CCObject *pSender);
//void testMSG(CCObject *pSender);将此函数搬到OtherLayer中
CREATE_FUNC(HelloWorld);
};
HelloWorld的实现:
bool HelloWorld::init()
{
bool bRet = false;
do
{
//
// super init first
//
CC_BREAK_IF(! CCLayer::init());
CCMenuItemLabel *labelItem = CCMenuItemLabel::create(CCLabelTTF::create("Send MSG","Arial",26),this,menu_selector(HelloWorld::sengMsg));
CCMenu *menu = CCMenu::create(labelItem,NULL);
this->addChild(menu);
bRet = true;
} while (0);
return bRet;
}
void HelloWorld::sengMsg(CCObject *pSender)
{
CCLOG("HelloWorld sendMSG");
CCNotificationCenter::sharedNotificationCenter()->postNotification("test",NULL);
}
OtherLayer层的实现:
#include "cocos2d.h"
using namespace cocos2d;
class OtherLayer : public CCLayer
{
public:
CREATE_FUNC(OtherLayer);
virtual bool init();
private:
void testMSG(CCObject *pData);
};
bool OtherLayer::init()
{
CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(OtherLayer::testMSG),"test",NULL);
return true;
}
void OtherLayer::testMSG(CCObject *pDATA)
{
CCLOG("OtherLayerMSG");
}
最后一件很重要的事情就是在HelloWorld的Scene中添加OtherLayer
CCScene* HelloWorld::scene()
{
CCScene * scene = NULL;
do
{
// 'scene' is an autorelease object
scene = CCScene::create();
CC_BREAK_IF(! scene);
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
CC_BREAK_IF(! layer);
OtherLayer *otherlayer = OtherLayer::create();
// add layer as a child to scene
scene->addChild(layer);
scene->addChild(otherlayer);
} while (0);
// return the scene
return scene;
}
现在我们的所有code部分已经完成看效果吧: