cocos2d-x 观察者设计模式

1、参考文章  http://blog.csdn.net/vanquishedzxl/article/details/23616535

  1. class HelloWorld : public cocos2d::CCLayer
  2. {
  3. public:
  4. virtual bool init();
  5. static cocos2d::CCScene* scene();
  6. void  sengMsg(CCObject *pSender);
  7. void testMSG(CCObject *pSender);
  8. CREATE_FUNC(HelloWorld);
  9. };
  1. bool HelloWorld::init()
  2. {
  3. bool bRet = false;
  4. do
  5. {
  6. //////////////////////////////////////////////////////////////////////////
  7. // super init first
  8. //////////////////////////////////////////////////////////////////////////
  9. CC_BREAK_IF(! CCLayer::init());
  10. CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(HelloWorld::testMSG),"test",NULL);
  11. CCMenuItemLabel *labelItem = CCMenuItemLabel::create(CCLabelTTF::create("Send MSG","Arial",26),this,menu_selector(HelloWorld::sengMsg));
  12. CCMenu *menu = CCMenu::create(labelItem,NULL);
  13. this->addChild(menu);
  14. bRet = true;
  15. } while (0);
  16. return bRet;
  17. }
  18. void HelloWorld::sengMsg(CCObject *pSender)
  19. {
  20. CCLOG("sendMSG");
  21. CCNotificationCenter::sharedNotificationCenter()->postNotification("test",NULL);
  22. }
  23. void HelloWorld::testMSG(CCObject *pSender)
  24. {
  25. CCLOG("testMSG");
  26. }

--实际用法demo

#define EventManager NotificationCenter::getInstance()

void PlayScene::init_listen(){
EventManager->addObserver(this, CC_CALLFUNCO_SELECTOR(PlayScene::handler_refresh_hand_card), GameEvent::handler_refresh_hand_card, NULL);
EventManager->addObserver(this, CC_CALLFUNCO_SELECTOR(PlayScene::handler_refresh_all_card), GameEvent::handler_refresh_all_card, NULL);
}

EventManager->postNotification(GameEvent::on_msg, sm);

EventManager->removeAllObservers(this);

上一篇:R(7): data.table


下一篇:监听HTML input输入框值的即时变化onpropertychange、oninput兼容IE,Chrome,FF,Opera等