开始
第一次运行
#ifndef EventListenerCustomTest_hpp
#define EventListenerCustomTest_hpp
#include <stdio.h>
#include "cocos2d.h"
USING_NS_CC;
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
using namespace cocos2d::ui;
class EventCustomTest :public Layer {
public:
static Scene* createScene();
bool init();
CREATE_FUNC(EventCustomTest);
Text* statusLabel;
};
#endif /* EventListenerCustomTest_hpp */
//
// EventListenerCustomTest.cpp
// Day01Demo
//
// Created by LXBig on 2018/6/5.
//
//
#include "EventListenerCustomTest.hpp"
Scene* EventCustomTest::createScene()
{
auto scene = Scene::create();
auto layer = EventCustomTest::create();
scene->addChild(layer);
return scene;
}
bool EventCustomTest::init()
{
if (!Layer::init()) {
return false;
}
auto btn = Button::create();
btn->setTitleText("Start");
btn->setTitleColor(Color3B::YELLOW);
btn->setTitleFontSize(25);
btn->setPosition(Vec2(240, 160));
this->addChild(btn);
static int count = 0;
btn->addClickEventListener([=](Ref* sender){
++count;
char* buf = new char[10];
sprintf(buf, "%d", count);
EventCustom event("event1");
event.setUserData(buf);
//发送用户数据
_eventDispatcher->dispatchEvent(&event);
CC_SAFE_DELETE_ARRAY(buf);
});
statusLabel = Text::create();
statusLabel->setString("test");
statusLabel->setPosition(Vec2(160, 230));
statusLabel->setColor(Color3B::YELLOW);
statusLabel->setFontSize(30);
this->addChild(statusLabel);
//cocos2dx观察者模式EventListenerCustom的使用(代替NotificationCenter)
// 创建一个监听事件,第一个参数是事件的键值名(事件名)
auto _listener = EventListenerCustom::create("event1", [=](EventCustom* event)
{
std::string str("event 1 received, ");
//接受char* 类型用户数据
char* buf = static_cast<char*>(event->getUserData());
str += buf;
str += " times";
statusLabel->setString(str.c_str());
});
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(_listener, this);
return true;
}