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

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


// clientone.jsvar piece = new BoardPiece();// ...socket.send(JSON.stringify(piece));// clienttwo.jsvar piece = BoardPiece.Create(JSON.parse(json));...// BoardPiece.jsfunction 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.