22 of Cocos2D-x game development: Basis of the CCNotificationCenter Observer Model (1)

Source: Internet
Author: User

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:



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.