Skip to content

Instantly share code, notes, and snippets.

@kaid
Created September 12, 2013 13:45
Show Gist options
  • Save kaid/6537630 to your computer and use it in GitHub Desktop.
Save kaid/6537630 to your computer and use it in GitHub Desktop.
JSONSerializable
guid = ->
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c)->
r = Math.random()*16|0
v = if c == 'x' then r else (r&0x3|0x8)
v.toString(16)
is_dom = (v)->
typeof jQuery != "undefined" &&
v instanceof jQuery ||
v instanceof Node
class JSONSerializable
serializable: true
toJSON: ->
@["#class"] = @constructor.name
@
clean_ref: ->
delete(@ref_id) if @ref_id
delete(@["#class"]) if @["#class"]
for key, value of @
if value instanceof Array
for item in value
item.clean_ref() if item.serializable
serialize: ->
cache = {}; counter = 0
result = JSON.stringify @, (k, v)=>
return if is_dom(v)
if v && v.serializable
return {ref: v.ref_id} if v.ref_id
v.ref_id = "#{v.constructor.name}@#{guid()}"
cache[v.ref_id] = v
v
@clean_ref()
result
@deserialize: (json)->
cache = {}
JSON.parse json, (k, v)->
if @ref_id
cache[@ref_id] = @
delete @ref_id
return cache[v.ref] if v.ref
if @["#class"]
@.__proto__ = window[@["#class"]]::
delete @["#class"]
v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment