关于cocos2dx观察者模式(CCNotificationCenter)

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必须是一样,否则监听不到,我们可以理解为必须是同一个频道。

大家轻喷     ------蛋蛋

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值