backbone-relational-hal
Consume HAL+JSON APIs with Backbone.js and Backbone-relational.js.
Requirements
backbone-relational-hal is currently tested with the following libraries:
- Underscore v1.7.0
- jQuery v2.1.1
- uri-templates v0.1.5
- Backbone.js v1.1.2
- Backbone-relational.js v0.8.8
Installation
With bower:
bower install --save backbone-relational-hal
Builds:
- Development: backbone-relational-hal.js
- Production: backbone-relational-hal.min.js
Usage
This library adds a new Backbone.RelationalHalResource
class that you can extend like Backbone.RelationalModel
or Backbone.Model
.
var Person = BackboneRelationalHalResource;
HAL Links
HAL Embedded Resources
Hyperlinks
HAL resources can parse HAL+JSON links out of the box.
Let's instantiate the above sample class and fetch data from the server.
var person = ;person;
Assume the server would return this data containing several links.
Use the link
method of a HAL resource to retrieve useful link objects.
// get a link objectpersonlink'self'; // => a Backbone.RelationalModel // get the href of a linkpersonlink'self'href; // => '/people/2' // get a list of linksvar alternates = personlink'alternate' all: true ; // => Backbone.Collection of link objects // get one of the links in the listalternateshref; // => '/people/2.html' // find a link matching criteria// (using Backbone's Underscore proxy methods)alternateshref; // => '/people/2.xml'
URI Templates
Templated links can be expanded using the uri-templates library.
// get a templated link without parameterspersonlink'search'href; // => '/people/2/search' // expand a link template with parameterspersonlink'search'href template: email: 'foo@example.com' ; // => '/people/2/search?email=foo@example.com'
Generating <a> Tags from Links
The tag
method of link objects can generate HTML link tags for you.
// simple tag with text contentpersonlink'self'; // => $('<a href="/people/2">John</a>') // HTML contentvar content = text'Jane';personlink'self'; // => $('<a href="/people/2"><strong>Jane</strong></a>')
Embedding Resources
Define embedded resources with the halEmbedded
property when extending a HAL resource.
Embedded resources are Backbone-relational.js relations and use the same options.
var Company = BackboneRelationalHalResource;
You can also use an equivalent HAL-like syntax where the key in the halEmbedded
object is automatically used as the relation key.
var Company = BackboneRelationalHalResource;
Assume the server would return this data for a company.
You can retrieve embedded resources with the embedded
method.
// get an embedded resourcecompany; // => Personcompany; // => 'Bill Lumbergh' // get a Backbone.Collection of embedded resourcesvar employees = company; // => Backbone.Collection // get one of the resources in the collectionemployees; // => Personemployees; // => 'Peter Gibbons'
Meta
- Author: Simon Oulevay (Alpha Hydrae)
- License: MIT (see LICENSE.txt)