1 |
Class("Joose.Storage", { |
2 |
meta: Joose.Role, |
3 |
|
4 |
methods: { |
5 |
// gets called by the JSON.stringify method |
6 |
toJSON: function () { |
7 |
return this.pack() |
8 |
}, |
9 |
|
10 |
pack: function () { |
11 |
|
12 |
if(this.meta.can("prepareStorage")) { |
13 |
this.prepareStorage() |
14 |
} |
15 |
|
16 |
var o = { |
17 |
__CLASS__: this.packedClassName() |
18 |
}; |
19 |
var me = this; |
20 |
|
21 |
var attrs = this.meta.getAttributes(); |
22 |
|
23 |
Joose.O.each(attrs, function (attr, name) { |
24 |
if(attr.isPersistent()) { |
25 |
o[name] = me[name]; |
26 |
} |
27 |
}) |
28 |
|
29 |
return o |
30 |
}, |
31 |
|
32 |
packedClassName: function () { |
33 |
var name = this.meta.className(); |
34 |
var parts = name.split("."); |
35 |
return parts.join("::"); |
36 |
} |
37 |
}, |
38 |
|
39 |
classMethods: { |
40 |
unpack: function (data) { |
41 |
var meta = this.meta |
42 |
var me = meta.instantiate(); |
43 |
var seenClass = false; |
44 |
Joose.O.each(data, function (value,name) { |
45 |
if(name == "__CLASS__") { |
46 |
var className = Joose.Storage.Unpacker.packedClassNameToJSClassName(value) |
47 |
if(className != me.meta.className()) { |
48 |
throw new Error("Storage data is of wrong type "+className+". I am "+me.meta.className()+".") |
49 |
} |
50 |
seenClass = true |
51 |
return |
52 |
} |
53 |
me[name] = value |
54 |
}) |
55 |
if(!seenClass) { |
56 |
throw new Error("Serialized data needs to include a __CLASS__ attribute.: "+data) |
57 |
} |
58 |
|
59 |
if(me.meta.can("finishUnpack")) { |
60 |
me.finishUnpack() |
61 |
} |
62 |
|
63 |
return me |
64 |
} |
65 |
} |
66 |
|
67 |
}) |