retain a cc.Scene object

Hi, I am converting a game from cocos2d-x with lua bindings to cocos2d-html5. I have a main menu scene and a slot scene. In the cocos2d-x version in the main menu code I create the slot scene and retain it for later use:

local slotScene = SlotScene()
slotScene:retain()

Then, when the user touches the play button I push the scene:

local function didTouchPlaySlot()
    CCDirector:sharedDirector():pushScene(CCTransitionCrossFade:create(1.0, slotScene))
end

The initialization of SlotScene is rather heavy and I don’t want the user to have to wait after touching the play button on the main menu. I also want the state of the slotScene to be saved when switching between the main menu scene and the slot scene.

The problem I’m having in cocos2d-html5 is that the slotScene instance is “undefined” in the didTouchPlaySlot callback:

    var MainMenuLayer = cc.Layer.extend({
    _slotScene:null,

    didTouchPlaySlot:function() {
        //ERROR this._slotScene is undefined!
        cc.Director.getInstance().pushScene(this._slotScene);
    },

    init:function () {
        this._super();

        //setup slot scene and cache for when they go to the main game
        this._slotScene = new SlotScene();
        this._slotScene.retain();

        //add the play slot button and do other stuff here

        this.setTouchEnabled(true);

        return true;
    }
});

I looked at the implementation of retain() and it is an empty method. Does anyone know how I can cache the _slotScene instance so it will not be undefined in the didTouchPlaySlot function?

I have tried your code. However, it works well.

I have added them in myApp.js of template.

Please download the attachment and try it yourself.

Hi Shun,

Thank you for attaching this code, it helped me to track down the problem in my code, I was passing a callback function around and not passing it’s scope, so I was being bitten by function level scoping.

Regards,
Jason

You are welcome. :slight_smile: