Cocos2D-X为我们准备了太多东西,当我们想要监听一个动作但是都不能老是盯在这一件事情上的时候就可以用他为我们量身定制的观察者模式,今天我们初步来学习一下这个传说很久的观察这模式在Cocos2D-X中的简单运用。
其实观察者模式的初步学习还是很简单的我们只要定义两个函数即可:
- classHelloWorld:publiccocos2d::CCLayer
- {
- public:
- virtualboolinit();
- staticcocos2d::CCScene*scene();
- voidsengMsg(CCObject*pSender);
- voidtestMSG(CCObject*pSender);
- CREATE_FUNC(HelloWorld);
- };
- #endif//__HELLOWORLD_SCENE_H__
然后在init()函数中添加事件的监听。在SendMSG()函数中发送事件消息。
boolHelloWorld::init()
boolbRet=false;
do
{
//////////////////////////////////////////////////////////////////////////
//superinitfirst
CC_BREAK_IF(!CCLayer::init());
CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(HelloWorld::testMSG),"test",NULL);
CCMenuItemLabel*labelItem=CCMenuItemLabel::create(CCLabelTTF::create("SendMSG","Arial",26), CCMenu*menu=CCMenu::create(labelItem,NULL);
this->addChild(menu);
bRet=true;
}while(0);
returnbRet;
}
voidHelloWorld::sengMsg(CCObject*pSender)
CCLOG("sendMSG");
CCNotificationCenter::sharedNotificationCenter()->postNotification("test",248);line-height:18px;list-style-position:outside !important;"> }
voidHelloWorld::testMSG(CCObject*pSender)
CCLOG("testMSG");
}
现在当我们点击菜单按钮式就可以看到事件被发送和接受的调试信息:
- 顶
- 0
- 踩
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。