简体   繁体   English

骨干渲染列表多次

[英]Backbone rendering list multiple times

I'm running into a problem while fetching json from the server and rendering it. 从服务器获取json并将其渲染时,我遇到了问题。 The issue is that every json object is got rendered again. 问题是每个json对象都被再次渲染。

var Student = Backbone.Model.extend({
    getConvertedToHash: function () {
        return $.extend({}, this.attributes.student[0], this.attributes.student[1], this.attributes.student[2]);
    }
});
var Group = Backbone.Collection.extend({
    model: Student,
    url: '/students.json'
});
var StudentView = Backbone.View.extend({
    tagName: 'li',
    className: 'alert alert-info',
    initialize: function () {
        _.bindAll(this, 'render');
    },
    render: function () {
        this.$el.html(this.model.getConvertedToHash().name);
        return this;
    }
});
var GroupView = Backbone.View.extend({
    el: $('.container'),
    initialize: function () {
        this.group = new Group();
        this.group.on('add', this.render, this);
        this.group.fetch({
            success: function () {
                console.log('Fetch successful!');
            },
            error: function(model, xhr, options) {
                console.log('error');
            }
        });
    },
    render: function () {
        var $ul = $('<ul>').addClass('student-list');
        this.group.each(function (student, index) {
            console.log(student.toJSON());
            var studentView = new StudentView({model: student});
            $ul.append(studentView.render().el);
        });
        this.$el.append($ul);
    }
});
var groupView = new GroupView();

Here's my json: 这是我的json:

[{
    "student": [{
    "name": "john",
    "lastName": "fox",
    "middleName": "yonson"
},{
    "age": 26,
    "gender": "male"
},{
    "passport": "qpuid5423",
    "inn": 123542
}]
},{
    "student": [{
    "name": "peter",
    "lastName": "powell",
    "middleName": "rivierra"
},{
    "age": 26,
    "gender": "male"
},{
    "passport": "qpuid5423",
    "inn": 123542
}]
}]

I got 2 objects in my json and all two objects are rendered, so instead of 1 list on a page I got 2 lists. 我在json中有2个对象,并且渲染了所有两个对象,所以我得到了2个列表,而不是页面上的1个列表。 Any thoughts? 有什么想法吗?

ANSWER! 回答! 'update' event worked for me. “更新”事件对我有用。 From specification "single event triggered after any number of models have been added or removed from a collection." 从规范“在添加或从集合中删除任何数量的模型后触发的单个事件”。 That's exactly what I needed. 那正是我所需要的。 Maybe that will help somebody who running into the same issue. 也许这会对遇到同样问题的人有所帮助。

'update' event worked for me. “更新”事件对我有用。 From specification "single event triggered after any number of models have been added or removed from a collection." 从规范“在添加或从集合中删除任何数量的模型后触发的单个事件”。 That's exactly what I needed. 那正是我所需要的。 Maybe that will help somebody who running into the same issue. 也许这会对遇到同样问题的人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM