Skip to content

Commit 7314eed

Browse files
committed
Merge branch 'gh-pages' of https://github.com/LivelyKernel/lively4-core into gh-pages
2 parents 6029414 + 10fa6a2 commit 7314eed

File tree

2 files changed

+43
-9
lines changed

2 files changed

+43
-9
lines changed

src/client/serialize.js

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,14 @@ export function serialize(obj) {
99
// 1st occurence: remember you saw that one
1010
const id = uuid();
1111
references.set(value, id);
12-
return Object.assign({ $id: id }, value);
12+
const result = Object.assign({ $id: id }, value);
13+
14+
const classToRemember = value.__proto__.constructor;
15+
if (classToRemember !== Object) {
16+
result.$class = classToRemember.name;
17+
}
18+
19+
return result;
1320
} else {
1421
return { $ref: references.get(value) };
1522
}
@@ -25,24 +32,37 @@ export function deserialize(json, classes = {}) {
2532
const idToObj = new Map();
2633

2734
function reviver(key, value) {
28-
if (value && value.$ref) {
35+
if (!value) {
36+
return value;
37+
}
38+
39+
if (value.$ref) {
2940
return idToObj.getOrCreate(value.$ref, () => ({}));
3041
}
3142

32-
if (value && value.$id) {
43+
if (value.$id) {
3344
const id = value.$id;
3445
delete value.$id;
3546

3647
if (idToObj.has(id)) {
3748
const proxy = idToObj.get(id);
3849

39-
return Object.assign(proxy, value);
50+
value = Object.assign(proxy, value);
4051
} else {
4152
idToObj.set(id, value);
42-
return value;
4353
}
4454
}
4555

56+
if (value.$class) {
57+
const className = value.$class;
58+
delete value.$class;
59+
60+
const classToRestore = classes[className];
61+
if (classToRestore) {
62+
value.migrateTo(classToRestore);
63+
}
64+
}
65+
4666
return value;
4767
}
4868

test/serialize-test.js

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,6 @@ const assert = chai.assert;
77

88
import { serialize, deserialize } from 'src/client/serialize.js';
99

10-
function isACopy(a, b) {
11-
12-
}
13-
1410
describe('simple serialization with JSON.{parse,stringify}', () => {
1511

1612
it('exports defined', () => {
@@ -80,4 +76,22 @@ describe('simple serialization with JSON.{parse,stringify}', () => {
8076
expect(o2).not.to.have.property('$ref');
8177
});
8278

79+
it('restore classes and clean up $class', () => {
80+
class A {
81+
get foo() { return 42; }
82+
}
83+
class B {
84+
get foo() { return 42; }
85+
}
86+
const a = new A();
87+
a.b = new B();
88+
a.b.a = a;
89+
const a2 = deserialize(serialize(a), { A, B });
90+
91+
expect(a).not.to.have.property('$class');
92+
expect(a2).not.to.have.property('$class');
93+
expect(a2 instanceof A).to.be.true;
94+
expect(a2.b instanceof B).to.be.true;
95+
});
96+
8397
});

0 commit comments

Comments
 (0)