Filtering collections versus multiple collections in Backbone?

When is it appropriate to filter a collection against having multiple collections in Backbone?

For example, consider a music library application. It will have a view for displaying genres and another view for displaying selected genre music.

Would you rather make one huge collection with all the music and then filter it out or a few smaller ones?

Having only one collection will allow you to add functions for filtering by other attributes, but suppose you have a lot of music: how can you download it when the application starts, if the user, if only 1 genre is needed

+6
source share
2 answers

I think that the simplest approach is a common unique collection, which, reasonably, fetch has already been filtered according to the genre from the server:

 // code simplified and no tested var SongsCollection = Backbone.Collection.extend({ model: Song, url: function() { return '/songs/' + this.genre; }, initialize: function( opts ){ this.genre = opts.genre; } }); var mySongsCollection = new SongsCollection({ genre: "rock" }); mySongsCollection.fetch(); 

You must make this collection to re-fetch data from the server at any time when the User changes the selected genre:

 mySongsCollection.genre = "punk"; mySongsCollection.fetch(); 
+4
source

This is mainly a design choice, but my vote was to choose a scheme that weakly reflects the database that stores collections.

If you are likely to store data in an SQL database, you will most likely have separate tables for songs and genres . You could connect them either through the genre_id column in the song table, or (if songs can have more than one genre) in terms of a separate song_genres join song_genres . Consequently, you will probably need separate collections representing genres and songs within them. In this case, backbone-relational can be a very useful tool to help keep them straight.

If you store information in any relational / key value / document repository, it makes sense to just save the genre directly in the song and filter it accordingly. In this case, you can save your keys / requests to the document so that you can directly access the songs (for example, through songs ) or through the genre (for example, genre:genre_id/songs ). If this is your route, it may be more convenient to simply create one huge collection of songs and plan to configure the appropriate filters both in the application environment and in the database.

+1
source

Source: https://habr.com/ru/post/915424/


All Articles