2015-08-20 07:25:56 +08:00
|
|
|
_ = require 'underscore'
|
|
|
|
|
|
|
|
# This keeps track of constructors so we know how to inflate serialized
|
|
|
|
# objects.
|
|
|
|
#
|
|
|
|
# If 3rd party packages want to register new inflatable models, they can
|
|
|
|
# use `register` and pass the constructor along with the name.
|
|
|
|
#
|
|
|
|
# Note that there is one registry per window.
|
|
|
|
class SerializableRegistry
|
|
|
|
constructor: ->
|
|
|
|
# A mapping of the string name and the constructor class.
|
|
|
|
@_constructors = {}
|
|
|
|
|
|
|
|
get: (name) -> @_constructors[name]
|
|
|
|
|
|
|
|
isInRegistry: (name) -> @_constructors[name]?
|
|
|
|
|
2015-08-22 07:05:30 +08:00
|
|
|
deserialize: (name, data) ->
|
|
|
|
if _.isString(data)
|
|
|
|
data = JSON.parse(data)
|
2015-08-20 07:25:56 +08:00
|
|
|
|
|
|
|
constructor = @get(name)
|
|
|
|
|
|
|
|
if not _.isFunction(constructor)
|
2015-08-22 07:05:30 +08:00
|
|
|
throw new Error "Unsure of how to inflate #{JSON.stringify(data)}"
|
2015-08-20 07:25:56 +08:00
|
|
|
|
|
|
|
object = new constructor()
|
|
|
|
object.fromJSON(data)
|
|
|
|
|
|
|
|
return object
|
|
|
|
|
|
|
|
register: (constructor) ->
|
|
|
|
@_constructors[constructor.name] = constructor
|
|
|
|
|
|
|
|
unregister: (name) -> delete @_constructors[name]
|
|
|
|
|
|
|
|
module.exports = SerializableRegistry
|