Several places in my Backbone application I\'d like to have an instant search over a collection, but I\'m having a hard time coming up with the best way to implement it.
The Collection associated with your CollectionView must be consistent with what you are rendering, or you'll run into problems. You should not have to empty your tbody manually. You should update the collection, and listen to events emitted by the collection in the CollectionView and use that to update the view. In your search method, you should only update your Collection and not your CollectionView. This is one way you can implement it in the CollectionView initialize method:
initialize: function() {
//...
this.listenTo(this.collection, "reset", this.render);
this.listenTo(this.collection, "add", this.addOne);
}
And in your search method, you can just reset your collection and the view will render automatically:
search: function() {
this.collection.reset(filteredModels);
}
where filteredModels
is an array of the models that match the search query. Note that once you reset your collection with filtered models, you'll lose access to the other models that were originally there before the search. You should have a reference to a master collection that contains all of your models regardless of the search. This "master collection" is not associated with your view per se, but you could use the filter on this master collection and update the view's collection with the filtered models.
As for your second question, you should not have a reference to the view from the model. The model should be completely independent from the View - only the view should reference the model.
Your addOne
method could be refactored like this for better performance (always use $el to attach subviews):
var view = new RowView({ model: model });
this.$el.find('tbody').append(view.render().el);