将JSON子阵列项拖入Backbone模板中

时间:2012-10-01 00:59:13

标签: json backbone.js

一个完整的Backbone新手的问题:

我想从JSON子阵列中提取项目并将它们放在我模板上的特定位置。我不确定如何定位这些特定项目。

子代表在下面的代码中表示:它是名为images的两个数组:

(function () {

//JSON object containing gallery content
var galleries = [
{ name: 'Renovations', images: [
    '../img/Galleries/01/pic01.jpg',
    '../img/Galleries/01/pic02.jpg'
    ]
},
{ name: 'Kitchens', images: [
    '../img/Galleries/01/pic03.jpg',
    '../img/Galleries/01/pic04.jpg'
    ]
}
];

//Gallery Class...this is a Backbone Model
var Gallery = Backbone.Model.extend({
 initialize: function(){
    console.log('this gallery is up and running');
}
});


//A collection...also a class & the 'C' in MVC in this case
var SingleGallery = Backbone.Collection.extend({
model: Gallery,
parse: function(response){
   return response.items;
   console.log(response.items);
}
});

//A view...also a class
var GalleryGroup = Backbone.View.extend({
tagName: 'article',
className: 'contact-container',
template: $('#galleryTemplate').html(),
render: function () {
    var tmpl = _.template(this.template);
    this.$el.html(tmpl(this.model.toJSON()));
    return this;
}
});

//Another view...also a class
    var GalleryView = Backbone.View.extend({
el: document.getElementById('container'),
initialize: function () {
    this.collection = new SingleGallery(galleries);
    this.render();
},
render: function () {
    var that = this;
        _.each(this.collection.models, function (item) {
        that.renderGallery(item);
    }, this);
},
renderGallery: function (item) {
    var galleryView = new GalleryGroup({
        model: item
    });
    this.$el.append(galleryView.render().el);
}
});

var gal1 = new GalleryView();

} ());

到目前为止,我的模板看起来像这样:

<script id="galleryTemplate" type="text/template">
<p><h1><%= name %></h1>
<div><img src='<%= images %>' /></div></p>
</script>

如果我只有一张图片要加载到&lt;%= images%&gt;这部分很简单,但我想构建一个格式良好的JSON对象,并能够找到两个“图像”数组中的每个单独项目。我想认为fetch()是要走的路,但我不确定......有什么想法吗?

提前致谢。 是

1 个答案:

答案 0 :(得分:2)

您可以使用下划线的each方法沿着这些行迭代images数组:

<% _.each(images, function (image) { %>
  <div><img src='<%= image %>' /></div>
<% }); %>