Skip to content

Instantly share code, notes, and snippets.

@mikekelly
Created May 28, 2012 11:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikekelly/2818604 to your computer and use it in GitHub Desktop.
Save mikekelly/2818604 to your computer and use it in GitHub Desktop.
Two small components for making Backbone play nicely with application/hal+json
window.HAL = {}
class HAL.Model extends Backbone.Model
constructor: (attrs) ->
super @parse(_.clone attrs)
parse: (attrs = {}) ->
@links = attrs._links || {}
delete attrs._links
@embedded = attrs._embedded || {}
delete attrs._embedded
return attrs
url: ->
@links?.self?.href || super()
class HAL.Collection extends Backbone.Collection
constructor: (obj, options) ->
super @parse(_.clone obj), options
parse: (obj = {}) ->
@links = obj._links || {}
delete obj._links
@embedded = obj._embedded || {}
delete obj._embedded
@attributes = obj || {}
if @itemRel?
items = @embedded[@itemRel]
else
items = @embedded.items
return items
reset: (obj, options) ->
# skip parsing if obj is an Array (i.e. reset items only)
obj = @parse(_.clone obj) if not _.isArray(obj)
return super(obj, options)
url: ->
@links?.self?.href
@jokull
Copy link

jokull commented Jul 13, 2012

How do you feel about .items there? Is it cool to just use "items" as the list of embedded things in an index type hal view?

On that note could the items be an attribute of the top level alongside _links and _embedded? It’s not outside the hal+json spec, but I'm just wondering about the conventions and ideas you have around typical index/collection/queryset resources.

@mikekelly
Copy link
Author

@jokull the default here is to use items because I wanted to pick a sensible default.. in practice I prefer to use a more specific name than 'items' e.g. 'widgets', 'dogs', 'invoices'.

We did discuss making items a top level property, but it's ont really worth it to be honest - this is what _embedded is for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment