0

My model looks like that:

  var Item = Backbone.Model.extend({
    urlRoot: '/item/ajax_get'
  });

If I want to get a specific item from the database, I can do: item = new Item({id: 11});

But what if I don't know the id of the item that I want to fetch? Instead, I want to query the database (via AJAX) to get the most recent item sorted by timestamp. Is this possible with Backbone.js?

trejder
  • 17,148
  • 27
  • 124
  • 216
Shamoon
  • 41,293
  • 91
  • 306
  • 570

1 Answers1

3

Backbone.js is designed for RESTful APIs so in those terms, what you're looking for is the first item of a collection sorted by the timestamp in descending order. That means what you're looking at is something like

GET /items/?count=1&sortBy=timestamp&order=descending

Which means you'd have something like the following code in backbone.js

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

var ItemCollection = Backbone.Collection.extend({
  model: Item,
  url: '/items/'
});

var collection = new ItemCollection();

collection.fetch({
  data: {
    count: 1,
    sortBy: 'timestamp',
    order: 'descending'
  }
}).then(function () {
  var myItem = collection.models[0];
}, function (error) {
  console.log(error);
});
Robert Verdes
  • 380
  • 3
  • 9
quinnirill
  • 814
  • 4
  • 6
  • Can this be sent as a POST, instead of a GET? – Shamoon Jul 27 '13 at 15:36
  • 2
    Sending it as `POST` instead of `GET` is not very restful; Backbone.js uses `POST` for saving newly created items. AFAIK you're going to have to use jQuery XHR directly, i.e. overwriting the `fetch` method of your model with something custom. – quinnirill Jul 27 '13 at 15:43