我刚刚让 socket.io 和 cocos2d-html5 工作。每次新客户端连接时,我都想在屏幕上放置一个新的 LabelTTF。 随着应用程序启动,我创建一个主层,其中 Tilemaplayer 作为子层,存储在 _tilemaplayer 中。
在我的主层上,我在 onEnter 中有以下代码:
var tilemap = new TilemapLayer();
this._tilemaplayer = tilemap;
this.addChild(tilemap);
socket = io.connect('hostname:port');
socket.on('connect', function(){
socket.emit('setName', {name: 'Testname'})
})
socket.on('newClient', function(data){
var testLabel = cc.LabelTTF.create(data.name, "Arial", 32);
this._tilemaplayer.addChild(testLabel);
})
为什么这会给我一个错误:this._tilemaplayer 未定义?我可以在主层的其他函数中访问它,为什么不在这里呢?
最佳答案
我认为您的 socket.on 事件处理函数中的“this”不等于您的图层或场景的“this”。
您需要保存图层或场景的“this”指针,代码如下:
var tilemap = new TilemapLayer();
this._tilemaplayer = tilemap;
this.addChild(tilemap);
socket = io.connect('hostname:port');
socket.on('connect', function(){
socket.emit('setName', {name: 'Testname'})
});
_this = this;
socket.on('newClient', function(data){
var testLabel = cc.LabelTTF.create(data.name, "Arial", 32);
_this._tilemaplayer.addChild(testLabel);
})
关于cocos2d-iphone - Cocos2d-html5 和 socket.io 这个未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15611576/