Created
May 28, 2012 11:19
-
-
Save mikekelly/2818604 to your computer and use it in GitHub Desktop.
Two small components for making Backbone play nicely with application/hal+json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
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.