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

16 篇文章 0 订阅
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());
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值