javascript - 主干渲染列表多次

标签 javascript json backbone.js

我在从服务器获取 json 并渲染它时遇到问题。问题是每个 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();

这是我的 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
}]
}]

我的 json 中有 2 个对象,并且所有两个对象都已渲染,因此页面上没有 1 个列表,而是有 2 个列表。有什么想法吗?

回答! “更新”事件对我有用。根据规范,“在集合中添加或删除任意数量的模型后触发单个事件”。这正是我所需要的。也许这会对遇到同样问题的人有所帮助。

最佳答案

“更新”事件对我有用。根据规范,“在集合中添加或删除任意数量的模型后触发单个事件”。这正是我所需要的。也许这会对遇到同样问题的人有所帮助。

关于javascript - 主干渲染列表多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31156092/

相关文章:

javascript - function(){}() 和 !function(){}() 有什么区别

json - 如何使package.json系统中的路径独立?

php - 在 PHP 中读取和显示 JSON 对象时遇到问题

php - 访问数组中的显式对象

node.js - Socket.IO - 打开的连接是一个问题吗?

javascript - 让主干路由与 pushstate 和 node.js/express 作为服务器一起工作

c# - 单选按钮未更新服务器端的值

javascript - 删除与我要删除的元素相邻的文本

javascript - react 未定义的 map 输出

javascript - 如何从商店中的模型中删除validationError?