Custom Events Javascript?

Hi,

I worked on a project (c++) using cocos2dx that used custom events like this:

To listen:

cocos2d::EventListenerCustom *_themeEventListener;

_themeEventListener = _eventDispatcher->addCustomEventListener(ThemeEvent::EVENT, [=](EventCustom* event) {

});
_themeEventListener->retain();

To raise event:

ThemeEvent* themeEvent = ThemeEvent::create();
themeEvent->retain();
Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(
	ThemeEvent::EVENT, themeEvent);
themeEvent->autorelease();

Is this possible using the javascript version???

Thanks,

Tim

Yes.

To create custom event:
var customEvent = new CustomEvent('MyCustomEvent', { detail: { //whatever you want here } });

To dispatch custom event:
window.dispatchEvent(customEvent);

To listen to custom event:
window.addEventListener('MyCustomEvent', function (e) { console.log(e); });

2 Likes

Thanks Dude, exactly what I was looking for !

It might though not work in native platforms, not sure, just a guess

Or it might work