如何使用Backbone解析JSON?

时间:2014-12-16 09:02:30

标签: javascript json backbone.js

我正在学习Backbone,只举一个例子。我有一个JSON网址,结果如下:

{
    help: "Help",
    success: true,
    result: {
        count: 13,
        results: [
            {
                name: "Name 1",
                description: "Desc 1",
                resources: [
                    {
                        img: "url.jpg"
                    }
                ]
            }, 
            {
                name: "Name 2",
                description: "Desc 2",
                resources: [
                    {
                        img: "url2.jpg"
                    }
                ]
            }
        ]
    }
}

现在我想将所有结果都放到HTML div中,所以我使用了这个:

$(function() {
    var Dataset = Backbone.Model.extend();

    var ProfileList = Backbone.Collection.extend({
        model: Dataset,
        url: 'profiles.json'    
    });   

    var ProfileView = Backbone.View.extend({
        el: "section#block-block-5",
        template: _.template($('#profileTemplate').html()),
        render: function(eventName) {
            _.each(this.model.models, function(profile){
                var profileTemplate = this.template(profile.toJSON());
                $(this.el).append(profileTemplate);
            }, this);

            return this;
        }
    });

    var profiles = new ProfileList();    
    var profilesView = new ProfileView({model: profiles});
    profiles.fetch({
        success: function(){
            profilesView.render();
        }
    });
});

<script id="profileTemplate" type="text/template">
    <div class="profile">
        <div class="info">
            <div class="name">
                <%= name %>
            </div>
            <div class="description">
                <%= description %>
            </div>
            <div class="image">
                <%= resources.url %>
            </div>
        </div>
    </div>
</script>

问题是我不知道如何在JSON响应中访问results组。

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

你应该使用parse函数将你的模型与results元素的result属性绑定

var ProfileList = Backbone.Collection.extend({
        model: Dataset,
        url: 'profiles.json',
        parse: function (response) {
          return response.result.results;      
        }    
    });