【发布时间】:2013-12-06 21:35:18
【问题描述】:
我有一个简单的节点 .js socket.IO 服务器,它正在工作,但我的事件回调中的范围不正确。如何从我的 client.on 处理程序中正确引用“客户端”?
sockIO.sockets.on('connection', function (client){
// new client is here!
console.log('A new user connected!');
//This WORKS!
client.emit('news', { msg: 'new user connected from socket server' });
client.on('customEvent', function (data) {
console.log('I received a custom event and data = ', data);
//following doesn't get called also 'client.emit' doesn't work
this.emit('foo', { msg: 'foo from socket server' });
});
客户端代码
<html>
<p id="text">socket.io</p>
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript" src="js/lib/jquery-1.4.2.min.js"></script>
<script>
$(document).ready(function(){
var socket = io.connect('http://localhost');
text = $('#text');
console.log('socket is '+socket);
socket.on('connect', function () {
$('#text').html('connected');
});
socket.on('news', function (info) {
$('#text').html(info.msg);
});
socket.on('foo', function (info) {
alert('YES foo received from server');
$('#text').html(info.msg);
});
socket.on('disconnect', function () {
$('#text').html('disconnected');
});
});
</script>
【问题讨论】:
-
你说它不起作用是什么意思?抛出异常还是无法解决?
-
永远不会被调用,否则无法调用未定义的方法'emit'
标签: javascript node.js scope socket.io