Skip to content

Instantly share code, notes, and snippets.

@JonMidhir
Created October 15, 2013 12:21
Show Gist options
  • Save JonMidhir/6990752 to your computer and use it in GitHub Desktop.
Save JonMidhir/6990752 to your computer and use it in GitHub Desktop.
# Assume response JSON for `book` looks like this:
# {
# id: 1,
# pages: [{
# id: 1,
# chapter: 1,
# text: 'It was the best of times, '
# }, {
# id: 2,
# chapter: 1,
# text: 'it was the splurst of times'
# }]
# }
#
#
# Backbone allows you to mutate the JSON before it parses it into
# an object by overriding the `parse` method. This allows you to
# do practically anything with any attribute and to add or remove
# attributes as you see fit; e.g.
#
# 1. Cast a currency value from integer to a string.
# 2. Multiply ruby epoch times by 1000.
# 3. Convert arbitrary JSON into your own objects.
class Models.Page extends Backbone.Model
class Collections.Pages extends Backbone.Collection
model: ShiftDock.Models.Page
class Models.Book extends Backbone.Model
# override the `parse` method, replacing relationships
# in the incoming JSON with their Backbone equivalent
parse: (response, options) ->
response.pages = @pagesCollectionFromJSON(response.pages)
# Create a pages collection from JSON array
pagesCollectionFromJSON: (_pages) ->
# Update existing collection or cast a new one
if @get('pages')
pages = @get('pages')
# ... You might want to edit the _pages JSON here, mix in your
# own stuff etc.
pages.set(_pages)
else
pages = new Collection.Pages(_pages)
# return the resultant collection
pages
# don't forget you may need to override toJSON as well
# e.g. *_attributes for rails accepts_nested_attributes_for
toJSON: ->
# serialize to JSON as normal
json = super
# Insert pages_attributes by serializing pages collection
json['pages_attributes'] = @get('pages').toJSON()
# Remove the original `pages` object from the JSON
delete json['pages']
# Return with the root node
{book: json}
# Basically the relationship is coming from the server as a JSON object or array, Backbone
# does nothing with it except add it as an object to the object you're creating.
#
# Fortunately you can override the methods that parse, intialize and serialize objects so
# that you can mutate the JSON before it is used to create the object.
#
# In this case we're looking at the JSON for a `pages` array and replacing it in the JSON with
# a `pages` Collection. You could do the same with a `has_one` association by replacing it in
# the JSON with a Model instead.
#
# After you do this it's up to you to listen for the updates you want on the relationship, e.g.
#
# @get('pages').on('change:text', @updateWordCount, this)
#
# @listenTo @get('pages'), 'change:text', @updateWordCount
#
# etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment