2013-03-25 3 views
2

나는 socket.io와 cocos2d-html5를 사용하고있다. 새 클라이언트가 연결될 때마다 새 LabelTTF를 화면에 표시하려고합니다. 응용 프로그램을 시작하면 _tilemaplayer에 저장되는 Tilemaplayer가 하위 레이어 인 메인 레이어가 만들어집니다. 내 주요 레이어에Cocos2d-html5 and socket.io this undefined

I 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); 
})