【问题标题】:Backbone how to get specific object in array骨干如何获取数组中的特定对象
【发布时间】:2015-03-18 09:50:58
【问题描述】:

我的 API 返回一个 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>

主干代码:

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

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

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

感谢任何帮助...

【问题讨论】:

  • 你的视图有模型吗,显示你的视图会有帮助

标签: javascript json backbone.js handlebars.js


【解决方案1】:

这里的问题是你的每辆车理想地应该是一个视图本身。因此,您的车把中不会有each,而是会为您的汽车收藏中的每个模型渲染一个ItemView。查看Marionette's CollectionViewItemView 以了解我的意思。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2021-07-15
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 2019-08-12
    • 2016-10-29
    相关资源
    最近更新 更多