我只是让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未定义的错误?我可以在我的主层的其他函数中访问它,为什么不能在这里呢?
发布于 2013-04-22 10:36:43
我认为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);
})https://stackoverflow.com/questions/15611576
复制相似问题