Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

observable cannot survive JSON.stringify #86

Closed
lilchow opened this issue Sep 4, 2015 · 5 comments
Closed

observable cannot survive JSON.stringify #86

lilchow opened this issue Sep 4, 2015 · 5 comments

Comments

@lilchow
Copy link

lilchow commented Sep 4, 2015

Let's say I created this simple object:

var a={};
a.obs=blocks.observable(2);

console.log(JSON.stringify(a)) would show only an empty object, i.e. "{}";

@astoilkov
Copy link
Owner

Hi @lilchow,

Sorry for the long long wait. I actually opened the issue and then forgot to answer it. The described behavior is expected. Observable objects are functions and JSON.stringify skips functions when stringifying objects.

In order to resolve your issue you could manually extract the values in an object and then call JSON.stringify.

var observable = blocks.observable(2);
var a = {};
a.obs = observable();

@Kanaye
Copy link
Collaborator

Kanaye commented Sep 25, 2015

You could also write a JSON.stringify replacer function, like so jsfiddle.

@astoilkov Maybe some function like this should be integrated into jsblocks?

Have a great day

@astoilkov
Copy link
Owner

Yeah. I like that idea. I am thinking of something like blocks.stringify that has a built in helper function like the one demonstrated in the jsfiddle example. What do you think?

@Kanaye
Copy link
Collaborator

Kanaye commented Sep 25, 2015

A blocks.stringify sounds good to me.
Maybe it should stay compatible to JSON.stringify and call the replacer function after replacing the observables.

@Kanaye
Copy link
Collaborator

Kanaye commented Oct 25, 2015

Or we implement a toJSON function which returns a string or just the plain value.
[edit:]
After playing a bit with toJSON: All browsers expect that toJSON return a 'normal' value not json (so the name is weird). If that function returns JSON it would get escaped, what's normaly not what the user wants.
[/edit]
I thought this way can't be cross browser compatible, but it works down to IE8 (I tested myself).
I think that way is better as it's not involving an function the user (or an other libary for e.g. ajax) has to call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants