Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

node.js - Passing an object with circular references from server to client-side Javascript while retaining circularity

I'm trying to pass an object with circular references from node.js server to client-side javascript.

Server (node.js):

var object = { circular: object }
//....
app.get('/', function(req, res){    
    res.render('index.jade', {object: object});
});

Client-side Jade/Javascript

script var object = !{JSON.stringify(object)};

Here I get the error that object contains circular references.

Any way to get the object in client-side javascript, with or without circular references?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Douglas Crockford has a solution for this that I have successfully used to solve this problem before: Cycle.js

instead of just using stringify and parse you would first call decycle and restore with retrocycle

var jsonString = JSON.stringify(JSON.decycle(parent));
var restoredObject = JSON.retrocycle(JSON.parse(jsonString));

JSFiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...