Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a "new" object in JavaScript in Socket.IO

I'm trying to pass objects from one client to another client, e.g. pieces in a multiplayer board game. I have a working solution using JSON.parser and __proto__, but I'm curious to know if there is a better way.

Client sends:

var my_piece = new BoardPiece();
// ... my_piece is assigned data, like x-y coordinates
socket.send(JSON.stringify(my_piece));

Server forwards the piece to others:

client.broadcast(piece);

Another client receives:

var your_piece = JSON.parse(json);
your_piece.__proto__ = BoardPiece.prototype; // provide access to BoardPiece's functions

It's the last step where I use __proto__ that I'm concerned I may be shooting myself in the foot. Is there a better suggestion?

like image 877
Brent Daugherty Avatar asked Mar 02 '26 03:03

Brent Daugherty


1 Answers

// clientone.js

var piece = new BoardPiece();
// ...
socket.send(JSON.stringify(piece));

// clienttwo.js
var piece = BoardPiece.Create(JSON.parse(json));
...

// BoardPiece.js
function BoardPiece() {

}

BoardPiece.prototype.toJSON = function() {
    var data = {};
    data.foo = this.foo;
    ...
    return data;
};

BoardPiece.Create = function(data) {
    var piece = new BoardPiece();
    piece.foo = data.foo;
    ...
    return piece;
}

Firstly using the toJSON method on your objects allows JSON.stringify to immediatly convert your object to JSON. This is part of the JSON API. The JSON API will call the toJSON method if it exists and converts that object to JSON.

This basically allows you to serialize your object as and how you want.

The second part is adding a factory method as a property of your constructor which takes your serialized JSON data and creates a new boardpiece. It will then inject your serialized data into that boardpiece object.

So your serializing only the data you care about and then passing that data through a factory method. This is the best way to send custom objects from one client to another.

like image 97
Raynos Avatar answered Mar 04 '26 18:03

Raynos