Backbone Collection不能完全从JSON填充

时间:2014-12-10 00:07:53

标签: javascript json backbone.js

我正在尝试从JSON数据填充Backbone集合。然而,在我尝试填充集合之后,我只会得到其中一个项目,当我应该得到12.有什么想法发生了什么?

JS:

(function ($) {


    var Sponsor = Backbone.Model.extend({
        defaults: {
            link: "http://www.google.com",
            photo: "http://placekitten.com/g/500/500"
        }
    });

    var Sponsors = Backbone.Collection.extend({
        model:  Sponsor,
        url: '../json/sponsors.json'
    });

    var SponsorView = Backbone.View.extend({
        tagName: "li",
        className: "sponsors-container",
        template: $("#sponsorTemplate").html(),
        render: function() {
            var tmpl = _.template(this.template);

            this.$el.html(tmpl(this.model.toJSON()));
            return this;
        }
    });

    var SponsorsView = Backbone.View.extend({
        el: $(".sponsors"),

        initialize: function() {
            this.collection = new Sponsors();
            this.collection.on("sync", this.render, this);
            this.collection.fetch();
        },

        render: function() {
            var that = this;
            _.each(this.collection.models, function(item) {
                that.renderSponsor(item)
            }, this);
        },

        renderSponsor: function(item) {
            var sponsorView = new SponsorView({
                model: item
            });
            this.$el.append(sponsorView.render().el);
        }
    });
    var sponsor = new SponsorsView();
} (jQuery));

JSON:

{
    "sponsors":[
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"}, 
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"}, 
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"}, 
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"}, 
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"},
        {"link":"http://google.com", "photo":"http://placekitten.com/g/500/500"}
    ]
}

HTML:

<ul class="sponsors"></ul>
<script id="sponsorTemplate"type="text/template">

            <a href="<%= link %>"><img src="<%= photo %>" /></a>

    </script>

1 个答案:

答案 0 :(得分:2)

您的数据是一个对象,而不是一个数组,这是骨干集合所期望的。

您有两种选择:

  1. 将数据更改为数组。
  2. 向集合中添加parse方法,该集合从结构中获取所需的数组:
  3. Backbone.Collection.extend({
      parse: function (payload) {
        return payload.sponsors
      }
    })