Cocos2D-X has prepared too many things for us. When we want to listen to an action, but we can't always stare at it, we can use the observer pattern he has tailored for us, today we are going to take a preliminary look at this legend for a long time to observe the simple use of this pattern in Cocos2D-X.
In fact, the preliminary study of the observer mode is very simple. We only need to define two functions:
class HelloWorld : public cocos2d::CCLayer{public: virtual bool init(); static cocos2d::CCScene* scene(); void sengMsg(CCObject *pSender);void testMSG(CCObject *pSender); CREATE_FUNC(HelloWorld);};#endif // __HELLOWORLD_SCENE_H__
Then add event listening to The init () function. Send event messages in the SendMSG () function.
bool HelloWorld::init(){ bool bRet = false; do { ////////////////////////////////////////////////////////////////////////// // super init first ////////////////////////////////////////////////////////////////////////// CC_BREAK_IF(! CCLayer::init());CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(HelloWorld::testMSG),"test",NULL);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("sendMSG");CCNotificationCenter::sharedNotificationCenter()->postNotification("test",NULL);}void HelloWorld::testMSG(CCObject *pSender){CCLOG("testMSG");}
Now, click the "click" button on the menu to view the debugging information sent and accepted by the event: