Search code examples
javascriptjsonbackbone.jshandlebars.js

Backbone how to get specific object in array


My API returns a JSON array like this:

cars:[
  { 
    "id" : "1",
    "fabrication" : "AUDI",
    "description" : "some text",
    "image"       : "some image"
  },
  { 
    "id" : "2",
    "fabrication" : "BMW",
    "description" : "some text",
    "image"       : "some image"
  },
  { "id" : "3",
    "fabrication" : "MERCEDES",
    "description" : "some text",
    "image"       : "some image"
  },
  { 
    "id" : "4",
    "fabrication" : "PORSCHE",
    "description" : "some text",
    "image"       : "some image"
  }    
]

So now, I have this list of data models rendered in a Handlebars HTMl template. My goal is, to click on an item, and then display the details for the clicked item.

Here is the HTML

<div>
  {{#each this}}
    <div>
      <a class="item" item-id="{{id}}>
        <h1>{{fabrication}}</h1>
        <img src="{{someimage}}" />
      </a>
    </div>
  {{/each}
</div>

The Backbone code:

events: {
   'click .item': 'showDetails'
},

showDetails:function(e) {
    e.preventDefault();
    var item = $(e.currentTarget).data('id');
}

So far so good, I get the correct id, but how do I get the rest of the data and display them in a new view?

Any help is appreciated...


Solution

  • The problem here is that each of your cars should ideally be a view itself. So you wouldn't have an each in your handlebars, instead you would render an ItemView for each model in your cars collection. Take a look at Marionette's CollectionView and ItemView to get an idea of what I mean.

    However, if you'd like to take your current approach, the following should work for you:

    showDetails:function(e) {
        e.preventDefault();
    
        var carId = $(e.currentTarget).data('id');
    
        var carModel = this.collection.findWhere({ id: carId });
    
        this.$('#extra-detail-container').html(new CarDetailView({ 
            model: carModel 
        }).render().el);
    }