0

I am writing a Backbone application where a user can search for video games.

The following piece of code gives back a random game that a user typed in using a searchfield. For example, if a user searches for Mario, it lists one of the top 5 five Mario games from the API.

$.getJSON(url, function(data){
  var games = data.results
  var game = games[Math.floor(Math.random() * 5)];
  var content = self.game_template({game: game});
  self.$el.append(content);
  $('.main-game').css("display", "block");
});

I would like that when a user searches for a particular title, that it renders every game. So when a user searches for Mario, all the Mario games render. The games are inside an array, so if I say, var game = games;, the Chrome inspector gives back Object, which contains a lot of other objects which are the games.

Robin van Dijk
  • 827
  • 7
  • 18

1 Answers1

0

If you're building a Backbone application, use Backbone pieces. All you have in your code is jQuery...

You should be using a Backbone Collection containing game models to store your data (see e.g. Backbone: Create collection from JSON). When you have a collection of games, you can use the filter method to get the list of games you want

var marioGames = myCollection.filter(function(game){
  return game.get("name").indexOf("Mario") >= 0;
});

marioGames will now be a collection of games containing the word "Mario" in their name property.

Community
  • 1
  • 1
David Sulc
  • 25,946
  • 3
  • 52
  • 54