- The code of the library: https://github.com/Planbox/backbone-subset
- The application live: http://tranquil-reaches-8635.herokuapp.com/
- The final code to the application: https://github.com/Planbox/Bookstore-example
Application StructureThe application is composed of 3 backbone views:
- Dashboard: To let the user enter new filters
- Criterias: The list of filters applied to the list
- List: the list of books itself
Creating and wrapping the collectionWe start by creating the collection Backbone-subset takes a backbone collection as a source in its constructor. Now we have a library containing our books. The library will provide us two things:
- Our filtered collection:
- Our list of filters:
library.filtersis an instance of
Subset.Filterswhich itself inherits from a Backbone Collection. It is now going to be possible to listen to modifications on
library.collection, and we will update our views when they are modified.
DashboardWe will start by making the dashboard. The html code is very simple, we have three attributes on which we want to filter our collection. Here is the code for the dashboard view: It is initialized with our library The view listens for the enter keypress event on a field. When that occurs, the attribute’s name and value are passed to a function which adds filters. It then cleans the fields of the dashboard.
As you probably guessed it, the addFilter function will insert new filters in the library.You can see that in addition to passing it the attribute and the values, we are providing it an operator. That’s because filters can work with both array or scalar attributes. Since title and author are both scalar values, we will make sure that the title or author of the book is in the list of titles or values that we entered. Categories being an array, we will just ask that one of its values is in the list of the values that we entered. There are other operators that you can use. Check it out on the github page: https://github.com/Planbox/backbone-subset