1

完全なバックボーン初心者からの質問:

JSON サブ配列からアイテムを取得し、テンプレートの特定の場所に配置したいと考えています。これらの特定のアイテムをターゲットにする方法がわかりません。

サブ配列は、次のコードで表されます。これは、images という名前の 2 つの配列です。

(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 %> セクションに読み込む画像が 1 つしかない場合、これは簡単ですが、適切にフォーマットされた JSON オブジェクトを構築し、2 つの「images」配列で個々の項目を見つけられるようにしたいと考えています。fetch() が進むべき道だと思いたいのですが、よくわかりません...何かアイデアはありますか?

前もって感謝します。は

4

1 に答える 1

2

アンダースコアのメソッドを使用して、次の行に沿っeachて配列を反復処理できます。images

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