您的位置:首页 > 移动开发 > Cocos引擎

Cocos2dx 提供的观察者模式工具类 CCNotificationCenter

2017-08-16 14:46 375 查看
Cocos2dx 提供的观察者模式工具类 CCNotificationCenter

1.addObserver(订阅消息)

2。removeObserver(取消订阅消息)

3.postNotification(发布消息)

同一资源文件的使用

.h:

//发布text消息
void sendMsg(CCObject *pSender);

//接收text消息的回调
void textMsg(CCObject *pSender);

.cpp:

bool HelloWorld::init()

{

    if ( !Layer::init() )

    {

        return false;

    }

    MenuItemImage*closeBtn = MenuItemImage::create("CloseSelected.png", "CloseNormal.png",this , 

menu_selector(HelloWorld::sendMsg));
closeBtn->setPosition(Vec2(visibleSize.width*0.1 , visibleSize.height*0.8));
Menu*menu = Menu::create(closeBtn , NULL);
menu->setPosition(Point(0,0));
addChild(menu);

//订阅消息类型为text的消息,不传递数据
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector

(MyHelloWorldScene::textMsg) ,"text" , NULL);

return true;

}

void HelloWorld::sendMsg( CCObject *pSender )

{
CCString*sData = CCString::create("HellWorld");
sData->retain();
CCNotificationCenter::sharedNotificationCenter()->postNotification("text" , sData);

}

void HelloWorld::textMsg( CCObject *pSender )

{
log("订阅成功");

}

不同资源文件夹的使用

HelloWorld.h:

//发布text消息
void sendMsg(CCObject *pSender);

HelloWorld.cpp:

Scene* HelloWorld::createScene()

{

  

    auto scene = Scene::create();

    auto layer = HelloWorld::create();

    MyHelloWorldScene *OtherLayer  =MyHelloWorldScene::create();  //接受消息层

    scene->addChild(layer);

    scene->addChild(OtherLayer);

    return scene;

}

bool HelloWorld::init(){

//发送消息

    MenuItemImage*closeBtn = MenuItemImage::create("CloseSelected.png", "CloseNormal.png",this , 

menu_selector(HelloWorld::sendMsg));
closeBtn->setPosition(Vec2(visibleSize.width*0.1 , visibleSize.height*0.8));
Menu*menu = Menu::create(closeBtn , NULL);
menu->setPosition(Point(0,0));
addChild(menu);

}

void HelloWorld::sendMsg( CCObject *pSender )

{
CCString*sData = CCString::create("HellWorld");
sData->retain();
CCNotificationCenter::sharedNotificationCenter()->postNotification("text" , sData);

}

MyHelloWorldScene.h:

//接收text消息的回调
void textMsg(CCObject *pSender);

MyHelloWorldScene.cpp:

bool MyHelloWorldScene::init() {
if (!Layer::init()) {
return false;
}
size = Director::getInstance()->getVisibleSize();

//订阅消息类型为text的消息,不传递数据
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector

(MyHelloWorldScene::textMsg) ,"text" , NULL);
return true;

}

void MyHelloWorldScene::textMsg( CCObject *pSender )

{
CCString*pData = (CCString*)pSender;
log("%s" , pData->getCString());

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: