Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HATEOAS and Backbone.js

I've started experimenting with Backbone.js, and was struck by the documentation for the documentation for the url property on Backbone.Model.

In particular, I'm building out a REST API that uses HATEOAS/hypermedia to drive the client(s).

I can see the usefulness of Backbone's default behaviour of building up URLs itself for items in a collection, but for my case, would prefer to have the model URLs built out of the data that is parsed.

Has anyone extended/built on Backbone to make it do this? Maybe building upon a "standard" like HAL?

EDIT:

For clarification, let's say I have the following:

GET /orders >>

[
  {
     "_links": {
       "self": "/orders/123"
     }
     "name": "Order #123",
     "date": "2012/02/23"
  },
  {
     "_links": {
       "self": "/orders/6666"
     }
     "name": "Order #666",
     "date": "2012/03/01"
  },
]

and I have an Order model like:

var Order = Backbone.Model.extend({
});

I would like the url property to be automatically pulled out of the "self" reference in the HAL. I think creating a new base model something like (not tested):

var HalModel = Backbone.Model.extend({
  url: function() {
    return get("_links").self;
  },
});

Thoughts?

like image 683
Pete Avatar asked Mar 01 '12 16:03

Pete


2 Answers

I've extended backbone to do exactly this, the library is available here:

https://github.com/mikekelly/backbone.hal

like image 86
Mike Avatar answered Oct 22 '22 21:10

Mike


Thanks for the clarification @Pete.

I think I see what your proposing and I suppose it could work. However, in your example, you first had to know the /Orders url before you were able to get the orders. And if you reworked your json to have an id property, you'd be pretty close to the default implementation of backbone.

Now if you just want to use a generic model or base model (e.g. HALModel) and just bootstrap it with data, your approach could be useful and definitely could work. However, I would look at overriding parse to pull the url out and set it on the model:

parse: function(response) {
    this.url = response._links.self;
    delete response._links;
    return response;
}
like image 24
timDunham Avatar answered Oct 22 '22 20:10

timDunham