Reputation: 1973
I have a CollectionView that generates this kind of list
<ul>
<li> All </li>
<li> Option 2</li>
<li> Option 2<li>
<ul>
All the Information about the second and third entry of this list is fetched from a DB. But I'd like to have the "All" option there as well. And I would like this option to be at the first position in my collection.
Only thing that came to my mind is to overwrite the MyCollection's add()
method. It works pretty well, but I'm just checking if there isn't a better/simpler way to do it.
MyCollection:
define([ 'underscore', 'backbone', 'models/MyModel'], function(_, Backbone, MyModel){
var MyCollection = Backbone.Collection.extend({
model: MyModel,
initialize: function(opts) {
this.options = opts;
this.add({name: "All", icon_class="all"}) /// this doesn't work
},
add: function(models, options) {
models.unshift({name:"All", icon_class:"all"})
return this.set(models, _.extend({merge: false}, this.options));
},
});
return MyCollection;
});
( On a side note, the collection itself is not fetching the data from DB. The fetch is actually called form a (let's call it a) ModelX
, which distributes the data to other collection that also make use of the same data.
So once the ModelX
finishes fetching all the data, it passes the data to all the required views.)
Upvotes: 2
Views: 52
Reputation: 48962
I think you have the right idea. Since you have separate models to represent the persistent data on the server, the data is this collection is clearly meant to represent view data, and so it's fine to put the All into the collection.
You could do it from within the collection or from an external "controller", depending on your architecture. You seem to want to do the former.
Your add
hack is quite ugly, though. It would be much cleaner to override the constructor. (See here for why doing it from initialize
didn't work.)
var MyCollection = Backbone.Collection.extend({
model: MyModel,
constructor: function(models, options) {
if (!models) models = [];
models.unshift({name:"All", icon_class:"all"});
Backbone.Collection.prototype.constructor.call(this, models, options);
},
}
Upvotes: 0
Reputation: 7133
I'm solving such problems on templating level. Because that element isn't really in your collection I wouldn't fake it:
<ul>
<li>All</li>
<% _.each(item, function (i) { %>
<li><%- i.name%></li>
<% }); %>
</ul>
Upvotes: 2