I have a Backbone model (let's call it Foo
) that includes a collection of n sub-models (let's call them Bar
), and in one particular view, I only want to display m of those sub-models, along with a message along the lines of "(n-m) remaining".
Right now, what I've got is something like this:
var FooView = Backbone.View.extend({
...
render: function() {
this._barViews = [];
var bars = this.model.get("bars");
var that = this;
_.each(bars.first(maxToShow), function(bar) {
that._barViews.push(new BarView({model:bar}));
}
var remaining = bars.length - maxToShow;
this.model.set("remaining", remaining > 0 ? remaining : undefined;
var json = this.model.toJSON();
$(this.el).html(this.template(json));
_(this._holdViews).each(function(hv) {
holdList.append($(hv.render().el));
});
}
});
This works, but it feels hacky, because I'm injecting "remainingMessage" into the model even though that's specific to this particular view. (Another view might show all the bars
, or none of them, and might or might not have a remaining message.) I'm also not totally excited about the nested views, since they mean creating an extra template file and having to remember to include it (FWIW, I'm using Handlebars.js for the templates, with server-side compilation).
Is there a better way to (1) filter the bars
collection down to maxShown
items, and (2) generate / include the number remaining in the view?