1

来自整个 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>

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

提前致谢。是

4

1 回答 1

2

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

<% _.each(images, function (image) { %>
  <div><img src='<%= image %>' /></div>
<% }); %>
于 2012-10-01T01:06:33.550 回答