我正在使用socket.io来创建交互式图形应用程序。在服务器端有一个图形变量。当用户加载页面时,测试事件被发送到服务器,服务器设置变量并将其返回给用户。我有第二个节点拖动事件,但是当我尝试拖动节点时,服务器表示图形的节点和链接变量未定义。
var express = require('express'),
app = express(),
http = require('http'),
socketIo = require('socket.io');
var server = http.createServer(app),
io = socketIo.listen(server);
var graph = {nodes : [], links : []}
server.listen(8080, function(){
console.log('server is listening on localhost:8080');
});
app.use(express.static(__dirname + '/'));
io.on('connect', function(socket){
// dump some test data
socket.on('test', function(){
// this just creates a few nodes in an array
var data = { ... }
graph = data;
io.emit('test', graph);
});
socket.on('eventNodeDragStart', function(index){
console.log('event node drag start: ' + index);
// undefiend, the graph.nodes is empty here
console.log(graph.nodes[index] + "\n\n");
// cannot read property of undefined
// also missing error handler on 'socket'
if(graph.nodes[index].locked) return;
graph.nodes[index].locked = true;
io.emit('eventNodeDragStart', index);
});
});
答案 0 :(得分:0)
通过替换此行来解决问题:
io.on('connect', function(socket){
用这个:
io.sockets.on('connect', function(socket){
不确定为什么会有效,但确实如此。