1
votes

Let say you are defining a Backbone.js Model. From the documentation we have ...

new Model([attributes], [options]) 

This seems great for passing some default attributes to a model. When passed the model automatically inherits those attributes and their respective values. Nothing to do. Awesome!

On they other hand lets say we have a Collection of that model.

new Backbone.Collection([models], [options])

Okay, cool we can pass some initial models and some options. But, I have no initial models and no options I need to pass so let's continue. I am going to fetch the models from the server.

collection.fetch([options])

Well I don't have any options, but I want to pass some attributes to add to each models as it is fetched. I could do this by passing them as options and then adding them to the attributes hash in the initialize for the model, but this seems messy.

Is their a Backbone.js native way to do this?

1
You could pass the attributes as options to fetch and over-ride the parse method in your collection to set the passed options (attributes) on your models. Check out parse.fbynite

1 Answers

2
votes

You can pass the attributes as options to fetch and over-ride the collection's parse method to extend the passed options (attributes) on the response.

The solution would look like the following:

var Collection = Backbone.Collection.extend({
  url:'someUrl',
  parse:function(resp,options) {
    if (options.attributesToAdd) {
      for (var i=0;i<resp.length;i++)
        _.extend(resp[i],options.attributesToAdd);
    }
    return resp;
  }
});

Then to add attributes when you call fetch on the collection, you can:

var collection = new Collection();

collection.fetch({
  attributesToAdd:{foo:'bar',more:'foobar'}
});

You may have to tweak the code a bit to work with your JSON structure, but hopefully this will get you started in the correct direction.