Wednesday, September 18, 2013

Fetch a Single Backbone.js Object via REST


In a previous post, I described how to fetch a collection using Backbone.js RESTful Persistence.  But, this morning, I was a little befuddled as to how to fetch a single object without fetching the entire collection.

The trick is to create a new model with the id attribute and add an options object to the model constructor with the urlRoot property.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
  <meta name="description" content="">
</head>
<body onload="onload();">
  <script src="jquery-1.10.1.js"></script>
  <script src="underscore.js"></script>
  <script src="backbone.js"></script>
  <script language="JavaScript"> function onload() {

// create a data model
var Person = Backbone.Model.extend({
  defaults: {
    name: '',
    age: 1
  }
});

// create a data model collection
var PersonCollection = Backbone.Collection.extend({
  model: Person,
  url: 'backbone.php'
});

var oneOff = new Person({id: 138}, {urlRoot: 'backbone.php'});
oneOff.fetch({
  success: function(model) {
    console.log(JSON.stringify(oneOff.toJSON()));
  }
});

}  </script>
</body>
</html>

But, of course, this required an improvement to PHP code in the "Backbone.js REST with PHP" post.  Until now, a GET request always returned the entire collection from backbone.php but I had to update it to check the request URI and, if an object was specified, to find and print that object only.

I've made over a dozen changes to the "Backbone.js REST with PHP" post since I originally published it; I just keep stumbling across new features and quirks which seem to only be covered in bits and pieces all over the Internet.

No comments:

Post a Comment