【问题标题】:Accessing a function stored in an object on server-side from client-side从客户端访问存储在服务器端对象中的函数
【发布时间】:2013-10-15 20:56:02
【问题描述】:

服务器端:

//When a player connects, all the players will get this message.
    game.sockets.emit('entrance', 
        {
            id: socket.id,
            players: [],
            message: 'Player ' + socket.id + ' is online', 
            store: function(id, object){
                this.players.push({id: id, object: object});
            }
        });

客户端:

socket.on('entrance', function(data){
        console.log(data.message);

        data.store(data.id, new Car('hero').init());    
    });

这给了我以下错误:

console.log的消息存储在对象中没有问题,所以它似乎是函数内部某处的错误。

谢谢!

【问题讨论】:

  • 您不能通过网络传输函数,它们不能作为 JSON 序列化。您的 data 对象将根本不包含 store 属性。每当您收到 entrance 事件(或从中构建整个 Player 实例)时,将其附加到客户端。

标签: javascript node.js object socket.io


【解决方案1】:

使用 socket.io,您通过网络发送 JSON 对象,而 JSON 不支持发送函数:http://www.json.org/

查看这篇文章的完整详细方法来做你想做的事情:Sending anonymous functions through socket.io?(这篇文章专门讨论了匿名函数,但同样适用于你正在尝试做的事情)。

【讨论】:

    猜你喜欢
    • 2016-11-16
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2012-05-19
    • 2016-01-03
    • 1970-01-01
    • 2012-12-07
    • 2012-04-08
    相关资源
    最近更新 更多