Backbone 如何获取数组中的特定对象

Backbone how to get specific object in array

我的 API returns 一个像这样的 JSON 数组:

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"
  }    
]

所以现在,我在 Handlebars HTMl 模板中呈现了这个数据模型列表。我的目标是,点击一个项目,然后显示被点击项目的详细信息。

这是HTML

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

Backbone代码:

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

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

到目前为止一切顺利,我得到了正确的 ID,但我如何获得其余数据并在新视图中显示它们?

感谢任何帮助...

这里的问题是您的每辆车都应该理想情况下本身就是一个视图。所以你不会在你的车把中有一个 each,而是你会为你的汽车集合中的每个模型呈现一个 ItemView。查看 Marionette's CollectionView and ItemView 以了解我的意思。

但是,如果您想采用当前的方法,以下方法应该适合您:

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);
}