簡體   English   中英

骨干渲染列表多次

[英]Backbone rendering list multiple times

從服務器獲取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個對象,並且渲染了所有兩個對象,所以我得到了2個列表,而不是頁面上的1個列表。 有什么想法嗎?

回答! “更新”事件對我有用。 從規范“在添加或從集合中刪除任何數量的模型后觸發的單個事件”。 那正是我所需要的。 也許這會對遇到同樣問題的人有所幫助。

“更新”事件對我有用。 從規范“在添加或從集合中刪除任何數量的模型后觸發的單個事件”。 那正是我所需要的。 也許這會對遇到同樣問題的人有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM