Pulling JSON subarray items into a template in Bac

2019-04-15 19:46发布

问题:

a question fron a total Backbone newbie:

I want to pull items from a JSON subarray and place them in a specific spot on my template. I'm not sure how to target those specific items.

The subarray is represented in the code below: it's the two arrays named 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();

} ());

My template looks like this so far:

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

If I only had one image to load into <%= images %> section, this would be easy, but I would like to construct a well-formatted JSON object and be able to find each individual item in the two 'images' arrays. I want to think that fetch() is the way to go but I'm not sure...any ideas?

Thanks in advance. is

回答1:

You could use underscore's each method to iterate over the images array along these lines:

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