Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a collection vs. several collections in Backbone?

Tags:

backbone.js

When is it appropriate to filter a collection vs. having several collections in Backbone?

For example, consider a music library app. It would have a view for displaying genres and another view for displaying the selected genre's music.

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

Having just one collection would allow you add features for filtering by other attributes as well, but suppose you have tons of music: how do you prevent loading it all in when the application starts if the user if only going to need 1 genre?

like image 561
wannabeartist Avatar asked May 10 '12 17:05

wannabeartist


2 Answers

I think the simplest approach is having a common unique Collection that, intelligently, fetch an already filtered by genre data 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 have to make this Collection to re-fetch data from the server any time the User changes the selected genre:

mySongsCollection.genre = "punk";
mySongsCollection.fetch();
like image 158
fguillen Avatar answered Oct 24 '22 02:10

fguillen


It's mostly a design choice, but my vote would be to choose a scheme that loosely reflects the database storing the collections.

If you're likely to be storing data in an SQL database, you will more likely than not have separate tables for songs and genres. You would probably connect them either via a genre_id column in the song table, or (if songs can have more than one genre) in terms of a separate song_genres join table. Consequently, you would probably want separate collections representing genres and the songs within them. In this case, backbone-relational might be very useful tool for helping keep them straight.

If you're storing information in any kind of relational/key-value/document store, it might make sense to simply store the genre with the song directly and filter accordingly. In this case, you might end up storing your document keys/queries in such a way that you could access songs either directly (e.g., via songs) or through the genre (e.g., genre:genre_id/songs). If this is the route you go, it may be more convenient to simply create a single huge collection of songs and plan to set up corresponding filters in both the application and database environment.

like image 26
rjz Avatar answered Oct 24 '22 02:10

rjz