Notification Center Extension for Cocos2d-x - Plunge Interactive

Notification Center Extension for Cocos2d-x

Today it will be about a small code snippet of a very useful class on Cocos2d-x usually unkonwn: The CCNotificationCenter class. This is a port ofthe iOS NSNotificationCenter class, that is very useful! Thanks to Cocos2d-x we can take the advantage of its features on all cocos2d-x supported platforms.

Why do we need this class? Imagine we have a class A, that calls a Class B. Class B will do something but we want A to keep working, then we want the class B to execute a method in class A to tell him that he has finished the job, and maybe send some arguments. So we have several ways to implement this functionality. For me the best and easiest are:

Each way has its advantages and disadvantages. Callbacks might be more robust in terms of code design, while CCNotificationCenter allows you to do “anything” “everywhere”, the callbacks force you to inherit classes and implement its virtual methods.

A small example of the implementation of this class would be:

// Define this at the header

// Add the cocos2d::extension namespace
using namespace cocos2d::extension;

// Add an observer for a notification type in your code:
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::myNotification), MY_NOTIFICATION, NULL);

// Raise the notification -note I'm sending an index value, that might be an object Tag or ID-
CCNotificationCenter::sharedNotificationCenter()->postNotification(MY_NOTIFICATION, (CCObject*)1);

// Handle the notification
void HelloWorld::myNotification(CCObject* obj)
    CCLOG("Notification achieved. ID: %i", (int)obj);

// Optionally, remove with the destructor, elsewhere the notification center will keep waiting for notifications (not necessarily bad, it depends on your architecture)
    CCNotificationCenter::sharedNotificationCenter()->removeObserver(this, MY_NOTIFICATION);

Easy right? Enjoy the class! Please feel free to follow us on twitter at @jboschaiguade and @plungeint

This site uses cookies to store information on your computer. Some cookies on this site are essential, and the site won't work as expected without them. Read more about them