Help me to find best approach for managing Backbone views.
For example I have a collection of views MyCollectionView which consists of MyModelView – views of each model in the collection.
And what if I want to hide/show some models on the page?
Now I am following this way:
- Use
collection.eachfor everymodel - Inside of loop I call model function
filterwith some params - In this function I check model properties and call
model.trigger 'hide'ormodel.trigger 'show' - And finally in the
model viewI usethis.model.bind 'hide', this.hide, thiswhere actually I use.hide()or.show()
This way seems me awful… Why do I need to do this long chain of functions and events. Does any simplest approach exist?
Thanks!
Your models shouldn’t be telling views what they should do – they are supposed to represent data and shouldn’t take part in controlling the application – so no wonders it feels wrong to you 🙂
The more elegant way would be to add a filter method to the MyCollectionView which would use underscore methods to filter the views you want to show/hide and do its job of well… doing that – picking which models should be shown. Then having hte array of matches just call a method for rendering the list and pass your array of models to it so it can render the views for matching models.
From my experience of creating such filters I can tell you that it might be much more efficient for longer lists to remove whole list do filtering on collection level and render again only the views which are matching the filter query. jQuery hide/show can be a bit taxing – though it’s a concern you will have only with large amount of data/views.
Also! Take advantage of the underscore methods bound to the collection – you don’t need to do
collection.each(...you can just do(Also remember to use documentFragment when rendering lists and appending to the DOM pre-generated list of views rather then appending them one by one)