简体   繁体   中英

Backbone rendering list multiple times

I'm running into a problem while fetching json from the server and rendering it. The issue is that every json object is got rendered again.

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:

[{
    "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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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