Saving and loading metadata in the backbone.js collection

I have a situation using backbone.js where I have a collection of models and additional information about models. For example, imagine that I am returning a list of sums: they have an amount associated with each model. Suppose now that the unit for each of the sums is always the same: say, quarts. Then the json object that I will return from my service might look something like this:

{ dataPoints: [ {quantity: 5 }, {quantity: 10 }, ... ], unit : quarts } 

Now basic collections do not have a real mechanism for naturally linking this metadata to the collection, but I was asked in this question: Setting attributes in the collection is js trunk , so I can expand the collection using the style function .meta(property, [value]) - This is a great solution. However, of course, we should be able to cleanly extract this data from a json response similar to the one we had above.

Backbone.js gives us a parse(response) function that allows us to specify where to retrieve a list of model collections from a combination with the url attribute. However, I do not know how to make a more intelligent function without overloading fetch() , which will remove the partial functionality that is already available.

My question is this: is there a better option than overloading fetch() (and trying to call it an implementation of a superclass) to achieve what I want to achieve?

thank

+14
json javascript collections
May 09 '11 at 2:25
source share
2 answers

Personally, I wrapped Collection inside another Model , and then override parse , for example:

 var DataPointsCollection = Backbone.Collection.extend({ /* etc etc */ }); var CollectionContainer = Backbone.Model.extend({ defaults: { dataPoints: new DataPointsCollection(), unit: "quarts" }, parse: function(obj) { // update the inner collection this.get("dataPoints").refresh(obj.dataPoints); // this mightn't be necessary delete obj.dataPoints; return obj; } }); 

Calling Collection.refresh() updates the model with new values. Passing a custom meta value to the Assembly, as suggested earlier, may prevent you from linking these meta values.

+22
May 09 '11 at 4:14
source share

This metadata is not a collection. It belongs to a name or other code descriptor. Your code should declaratively know that its collection is filled only with quartz elements. This is already happening, since url points to quartz elements.

 var quartzCollection = new FooCollection(); quartzCollection.url = quartzurl; quartzCollection.fetch(); 

If you really need this data, why don't you just call

_.uniq(quartzCollecion.pluck("unit"))[0];

0
May 09 '11 at 9:00
source share



All Articles