Get /collection/id in backbone without loading the entire collection
11,123
Solution 1
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()
Solution 2
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))}});
Solution 3
collection.fetch( {data: { id:56 } } )
Solution 4
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.
Comments
-
yves amsellem almost 2 years
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 thatGET
can be done/collection[/id]
but not how. -
yves amsellem almost 13 yearsThe following code does not work:
url: '/rest/product/'+this.id
-
Raynos almost 13 years@yvesamsellem after reading more carefully,
.url
needs to be a function -
yves amsellem almost 13 years@Raynos thanks. Is there a way to not repeat the url in the model and the collection?
-
Raynos almost 13 years@yvesamsellem The only way I can think is to extend the collection. With lazy loading functionality
-
yves amsellem almost 13 years@Raynos can you please complete your answer with a sample of code?
-
Raynos almost 13 years@yvesamsellem That's not simple functionality to implement. I might have a go at it later.
-
MrFoh over 11 yearsThis works better and can easily be added to Backbone's collection prototype
-
SimplGy almost 11 yearsAre you sure it's ok to use
model.id = productId
instead ofmodel.set('id', productId)
? -
yves amsellem almost 11 yearsYep, sure. The model uses this.id which is not a backbone attributes. Using model.set('id', ..) requires to use model.get('id') in his proper class. Both works, mine won't interfere with the backbone model attributes :D
-
Shubh over 10 yearsWorks as expected +1. But it gives me error after the execution of above line.
Uncaught TypeError: object is not a function
. Can you help?