Underscore-Awesomer: _.parseJSON for CouchDB model

This is an example showing a recent modification to _.parseJSON. Besides introducing a convention for serializing plain-old-JSON (POJ) into live instances, what I wanted to do was 1) introduce some flexibility into which field is used to look up the parseJSON methods, and 2) provide a way to not pollute the global namespace with your parseJSON methods.

# set up for CouchDB 'type' convention 
# make a Constructors namespace known to Underscore
root = this; root.Constructors||root.Constructors={}

class SomeModel
  constructor: (@key, @value) ->
  toJSON = -> return { type:'some_model', key:this.key, value:this.value }
  @parseJSON = (json) ->
    throw new Error('unexpected type') if (json.type!='some_model')
    return new SomeModel(json.key, json.value)
root.Constructors.some_model = SomeModel # add constructor to Constructors namespace

# assume this comes back from the server
json = {type:'some_model', key:'abcdef', value: {x:1, y:2, z:3} }

# deserialize - _.parseJSON finds 'root.Constructors.some_model'
some_model_instance = _.parseJSON(json)

Personal uses: Using my Backbone-Articulation.js library (Backbone-Articulation.js), I now automatically serialize the JSON from the server into instances inside my model attributes on the client. It means I am able to combine data with functionality on the client behind-the-scenes and just start interacting with the attributes directly.

You can find this example and more here: https://github.com/kmalakoff/examples-kmalakoff


Download now (Right-click, and use “Save As”):

Or check out the project here: https://github.com/kmalakoff/underscore-awesomer