Get / collect / identifier in the trunk without loading the entire collection

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

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

The following code can load the entire collection using collection.fetch() , but how to load one model? The mock documentation clearly states that GET can be done /collection[/id] , but not.

+7
source share
6 answers

While we set

 url:"api/user" 

for a collection, the equivalent of a model is

 urlRoot:"api/user" 

this will force the spine to automatically add / id when retrieving ()

+7
source

The model should be declared as follows:

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

Usage is simple:

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

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

+4
source

I have done 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)}); 

There is nothing more to guess if the model is already in the collection !. However, you should use a callback because you cannot depend on the result of the intimidation. You can use async false to get around this limitation.

+1
source

just .fetch Model.

So, create a model with its own .url function.

Something like

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

I have done 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(); 

The advantage of this is that you don't use the REST storage engine (instead, use something like local HTML5 storage or so on)

0
source

All Articles