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 multipla开发者_如何转开发yer 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?
// 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.
There are a bunch of object syncing projects for node that might make life easier. For starters, check out:
- NowJS
- node-object-sync
- Re-using Backbone.js Models on the server with Node.js and Socket.io to build real-time apps
Have tou tried jQuery's $.extend() method? http://api.jquery.com/jQuery.extend/
精彩评论