zalow517 zalow517 - 2 years ago 109
Javascript Question

How to listen for mobile Back event in Cocos2D-JS v3?

I can't seem to find any sources that show how to listen for when the user presses the Back button on a mobile device. Has it been implemented yet?

Answer Source

It appears that you can simply listen to the keydown event:

Assuming you've read how the event listener works in Cocos2D-JS v3:

First add a keyboard event listener:

var keyboardListener = cc.EventListener.create({
   event: cc.EventListener.KEYBOARD,
   onKeyPressed:  function(keyCode, event){
      if(keyCode == cc.KEY.backspace){
         //do something
      }else if(keyCode == cc.KEY.home){
         //do something

Then attach the listener to your layer:

cc.eventManager.addListener(keyboardListener, aLayer);

This answer was extracted from the official forums.

Note that it appears to be some cases in wich the keyCode for the home and back buttons won't be the ones expected, if you encounter this problem try printing to the console what keyCode is being recorded when you hit said keys.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download