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

I am trying to transfer objects from one client to another client, for example. pieces in a multiplayer board game. I have a working solution using JSON.parserand __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));

The 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 functions

This is the last step in which I use __proto__, what bothers me, that I can shoot in the leg. Is there a better suggestion?

+3
source share
3 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;
}

toJSON JSON.stringify JSON. JSON API. API JSON toJSON, , JSON.

.

factory , JSON . .

, , , factory. .

+8

Have you tried the jQuery $ .extend () method? http://api.jquery.com/jQuery.extend/

0
source

All Articles