简体   繁体   中英

Accessing a function stored in an object on server-side from client-side

Server-side:

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

Client-side:

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

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

This gives me the following error:

在此处输入图片说明

It console.log 's the message stored in the object without a problem, so It seems like the error somewhere inside the function.

Thanks!

With socket.io, you're sending JSON objects over the wire, and JSON doesn't support the sending of functions: http://www.json.org/

See this post full a detailed approach to do what you're trying to do: Sending anonymous functions through socket.io? (the post talks specifically about anonymous functions, but the same holds true for what you're attempting).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM