0

In backbone.js, is it possible to add an additional attribute to a collection? I have a model attached to it, but need to define a common attribute for all model entities that I would naturally see located best at the collection level.

Any thoughts?

orange
  • 7,755
  • 14
  • 75
  • 139
  • Should it be possible to listen to changes of that common attribute? – Yaroslav Oct 15 '12 at 10:12
  • May be this question discussion can help: http://stackoverflow.com/questions/5930656/setting-attributes-on-a-collection-backbone-js – mumu2 Oct 15 '12 at 13:02
  • Any code examples ? what would be this used for ? – Cristiano Fontes Oct 15 '12 at 14:04
  • In my instance, it was to keep track of a user's selection. I had a number of comments which were accessible by user name and the currently selected user's comment was meant to be displayed. The collection held all comments. I couldn't find a better place to store the selected user name at (maybe there is)... – orange Oct 16 '12 at 23:34

1 Answers1

1

This is javascript, everything is possible! You can attach anything to collection's constructor function, to collection's prototype, to a concrete instance of the collection. And the same is true for models.

// #1
var YourCollection = Backbone.Collection.extend({}, {sharedAttribute : 1});
var collection = new YourCollection();
console.log(collection.constructor.sharedAttribute); // 1

// #2
var YourCollection = Backbone.Collection.extend();
YourCollection.sharedAttribute = 2;
var collection = new YourCollection();
console.log(collection.constructor.sharedAttribute); // 2

// #3
var YourCollection = Backbone.Collection.extend();
YourCollection.prototype.sharedAttribute = 3;
var collection = new YourCollection();
console.log(collection.sharedAttribute); // 3

// #4
var YourCollection = Backbone.Collection.extend();
var collection = new YourCollection();
collection.sharedAttribute = 4;
console.log(collection.sharedAttribute); // 4
Yaroslav
  • 4,543
  • 5
  • 26
  • 36
  • The problem was that the toJSON method didn't return the modified collection properly, but I resolved this by overloading the method (actually I wrote a new one). – orange Oct 16 '12 at 23:32