cocos2d-iphone - Cocos2d-html5 和 socket.io 这个未定义

标签 cocos2d-iphone socket.io

我刚刚让 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/

相关文章:

cocoa - Mac 上的 UITouch 等效项

iphone - 如何在 tmx map 中提取折线点?

javascript - 查看套接字是否等于 null

node.js - 我的 nodejs 0.10.2 + Express 3.x + socket.io 0.9.11 出现错误

javascript - 执行 1 分/60 秒后连接丢失

iphone - Cocos2D iPad Vector Sprites/Spritesheet 创建

ios - 带圆角的 CCLayer

node.js - 根据客户端 POST 表单的字段切换套接字 [ Sails Node js ]

javascript - Socket.io 与 Heroku

iphone - GL_CLAMP_TO_EDGE 应该用在 NPOT 纹理中