2013-03-25 17 views
2

我只是讓socket.io和cocos2d-html5工作。每次連接新客戶端時,我都希望在屏幕上放置一個新的LabelTTF。 隨着應用程序的開始,我創建了一個Tilemaplayer作爲孩子存儲在_tilemaplayer中的主圖層。Cocos2d-html5和socket.io這個undefined

在我的主層我在的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沒有定義?我可以在我的主層的其他功能中訪問它,爲什麼不在這裏?

回答

2

我認爲你的socket.on事件處理函數中的「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); 
})