您的位置:首页 > 其它

CCNotificationCenter处理消息事件

2013-09-25 20:54 337 查看
define CLICK_TEST_MSG "whatever_unique"

// 添加监听
void GameMgr::addListener() {
CCNotificationCenter* t_pNotiCenter = CCNotificationCenter::sharedNotificationCenter();
SEL_CallFuncO t_oCallFuncO = callfuncO_selector(GameMgr::onClickTest);
t_pNotiCenter->addObserver(this, t_oCallFuncO, CLICK_TEST_MSG, NULL);
}

// 派发事件
void GameMgr::dispatchEvent() {
CCNode* t_pNode = new CCNode();
CCString* t_pCcStrMsg = new CCString("i love u!");
t_pNode->setUserData(t_pCcStrMsg);

CCNotificationCenter* t_pNotiCenter = CCNotificationCenter::sharedNotificationCenter();
t_pNotiCenter->postNotification(CLICK_TEST_MSG, (CCObject*)t_pNode);
}

// 事件响应
void GameMgr::onClickTest(CCObject* in_pCcObjData) {
CCNode* t_pNode = (CCNode*)in_pCcObjData;
CCString* t_pCcStrMsg = (CCString*)t_pNode->getUserData();
CCMessageBox(t_pCcStrMsg->getCString(), "Message");

// 传递完毕不要忘记释放内存
t_pCcStrMsg->release();
t_pNode->release();
}

// 移除监听
void GameMgr::removeListener() {
CCNotificationCenter* t_pNotiCenter = CCNotificationCenter::sharedNotificationCenter();
t_pNotiCenter->removeObserver(this, CLICK_TEST_MSG);
}


 

然后写个小程序来实践下这个。

改用系统为我们创建的Helloworld,首先将系统中建立退出按钮的代码注释掉。

然后Helloworld::init中末尾这样写

 

CCSprite *button = CCSprite::create("CloseNormal.png");
button->setPosition(ccp(200,300));
CCNode* t_pNode = new CCNode();

t_pNode->setUserData(button);

CCNotificationCenter* t_pNotiCenter = CCNotificationCenter::sharedNotificationCenter();
t_pNotiCenter->addObserver(this, callfuncO_selector(HelloWorld::onClickTest), CLICK_TEST_MSG, NULL);

CCNotificationCenter::sharedNotificationCenter()->postNotification(CLICK_TEST_MSG, (CCObject*)t_pNode);

this->addChild(button);


最后添加响应函数

void HelloWorld::onClickTest(CCObject* obj)
{
CCNode *temp =(CCNode*)obj;
CCSprite *button =(CCSprite*)temp->getUserData();
button->setPosition(ccp(100,100));

}


 

最后看运行截图,看看按钮的位置。 证明事件真的被执行了。成功



 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: