ST80
ST80

Reputation: 3903

BackboneJS fetch collection based on parameters

I want to display multiple musical artists based on the genre in a view. So, first of all I have my menu tabs:

<a data-name="hiphop" class="genre">HipHop</a>
<a data-name="rock" class="genre">Rock</a>
<a data-name="alternative" class="genre">Alternative</a>
<a data-name="jazz" class="genre">Jazz</a>

then my genre.js contains:

Genres.Collection = Backbone.Collection.extend({
    url: function() {
        return 'path to my json';
    },
    parse: function(response, genre){
        return response.data.genres[genre];
       // when I do: return response.data.genres.rock;
       // I get all artists from the genre "rock".
       // but I want the response to be based on the variable "genre"
    }           
});

then, in my mainView.js:

events: {
    'click .genre' : 'genre'
},

genre: function(event, genre){
    event.preventDefault();
    // get the clicked genre
    var genreName = $(event.target).data('name');
    var genresCollection = new Genres.Collection({genre:genreName });
    genresCollection.fetch();
    this.insertView('.genres', new Genres.View({collection: genresCollection}));                    
},

but no matter which genre I click, I get an empty Collection. can someone tlel me what I'm doing wrong here?

Many thanks!

Upvotes: 0

Views: 53

Answers (2)

nikoshr
nikoshr

Reputation: 33364

Options are not stored by default, but you can override your initialize method to provide this functionality. You would then use this stored value in your parse method :

Genres.Collection = Backbone.Collection.extend({
    url: function() {
        return 'path to my json';
    },
    initialize: function(opts) {
       opts = opts || {};
       this.genre = opts.genre || 'rock';
    },
    parse: function(response){
        return response.data.genres[this.genre];
    }           
});

Upvotes: 2

Trace
Trace

Reputation: 18889

You need to define a success callback. Try:

var genresCollection = new Genres.Collection(); 
genresCollection.fetch({
    data: {
        genre: genreName 
    },
    success: (function (coll_genres) {
        console.log(coll_genres.toJSON());
    }),
    error: (function (e) {
        console.log(e);
    })
});

Upvotes: 1

Related Questions