cocos2dx的观察者模式可以很好的解决不同类之间信息传递的问题,特别适合当精灵改变状态时在其他类或者函数的一个监听。
1postNotification函数(发布消息)
void postNotification(const std::string & name) 根据某个名字发送一个通知事件.
const std::string & name: 消息名称
void postNotification(const std::string & name,Ref * sender) 根据某个名字发送一个通知事件.
const std::string & name: 消息名称
Ref * sender: 要传输的数据
2 addObserver函数 (订阅消息)
void addObserver(Ref * target,SEL_CallFuncO selector,const std::string & name,Ref * sender)
根据指定的target,添加观察者.
Ref * target :要订阅消息的主体
SEL_CallFuncO selector :消息回调函数
std::string & name:消息名称
Ref * sender :要传递的数据
我这里就在一个类实现,逻辑主要就是点击按钮发送一个消息,然后我在init每秒调用一个订阅消息的函数receive(float),当点击按钮后,我这个函数就会受到这个消息。话不多说,直接上代码:
发布消息:
void NotificationCenterTest::sendMsg(CCObject* pSender){ //此函数是一个点击按钮后调用的函数,当点击按钮后消息发出
//发布test消息
auto sData = CCString::create("I am Here");
sData->retain();
CCNotificationCenter::sharedNotificationCenter()->postNotification("test",sData);
//CCNotificationCenter::shard->postNotification("test",sData);
}
订阅消息:
void NotificationCenterTest::receive(float)
{
CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(NotificationCenterTest::testMsg),"test",NULL);
}
void NotificationCenterTest::testMsg(CCObject* pSender){
auto msg = (CCString*)pSender;
CCLOG("testMsg: %s",msg->getCString());
}
点击按钮后的效果:
这里有一点需要注意的是postNotification和addObserver这里的test必须是一样,否则监听不到,我们可以理解为必须是同一个频道。
大家轻喷 ------蛋蛋