7
votes

Is there a way to load a single entity of a Backbone collection (from the server)?

Backbone.Collection.extend({
  url: '/rest/product'
});

The following code can load the entire collection with a collection.fetch() but how to load a single model? Backbone's documentation says clearly that GET can be done /collection[/id] but not how.

6

6 Answers

9
votes

The model has to be declared that way:

Backbone.Model.extend({
  url: function() {
    return '/rest/product/'+this.id;
  }
});

Using it is simple as:

var model = new ProductModel();
model.id = productId;
model.fetch({ success: function(data) { alert(JSON.stringify(data))}});
7
votes

While we set

url:"api/user" 

for the collection, the equivalent for the model is

urlRoot:"api/user"

this will make backbone automatically append the /id when you fetch()

4
votes

collection.fetch( {data: { id:56 } } )

1
votes

I did this:

Catalog.Categories.Collection = Backbone.Collection.extend({
fetchOne : function (id, success) {
    var result = this.get(id);
    if (typeof result !== 'undefined') {
        console.log(result, 'result')
        success.apply(result);
        return;
    }
    var where = {};
    where[this.model.prototype.idAttribute] = id;
    var model = new this.model(where);
    this.add(model);
    console.log(this._idAttr, where, this.model)
    model.fetch({success: function () {
        success.apply(model);
    }});
}
};

Now call it:

collection.fetchOne(id, function () {console.log(this)});

No more guessing if the model is already in the collection!. However, you have to use a call back as you can't depend on an intimidate result. You could use async false to get around this limitation.

0
votes

just .fetch a Model.

So create a model with it's own .url function.

Something like

function url() {
  return "/test/product/" + this.id;
}
0
votes

I did this:

var Product = Backbone.Model.extend({});
var Products = Backbone.Collection.extend({
  model: Product,
  url: '/rest/product'
});
var products = new Products();
var first = new Product({id:1});
first.collection = products;
first.fetch();

This has the advantage of working when you're not using a REST storage engine (instead, using something like the HTML5 Local storage, or so forth)