拉JSON子阵项目到骨干模板 [英] Pulling JSON subarray items into a template in Backbone

查看:87
本文介绍了拉JSON子阵项目到骨干模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

弗朗共骨干新手的问题:

a question fron a total Backbone newbie:

我想从一个JSON子阵拉项目,并把它们在我的模板的特定位置。我不知道如何针对那些特定的项目。

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.

子阵列重新$ P $下面在code psented:这是两个阵列命名的图片:

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>

如果我只有一个图像加载到&LT;%=影像%>部分,这将是容易的,但我想构建一个格式良好的JSON对象,并能找到两个各个项目图像的阵列。我想认为,取()是要走的路,但我不知道...任何想法?

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

推荐答案

您可以使用下划线的 方法来遍历图片沿着这些路线数组:

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

这篇关于拉JSON子阵项目到骨干模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆