Backbone 视图有问题

Having an issue with Backbone View

我是 Backbone 的新手,正在尝试完成一些简单的任务,例如从模型中呈现名称列表。但我收到此错误:

'cannot read property "model" of undefined'

我非常感谢对此提供的任何帮助以及任何一般提示。

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,
    initialize: function () {
        this.add(new Student({
            student: [
            {
                "name": "john",
                "lastName": "fox",
                "middleName": "yonson"
            },{
                "age": 26,
                "gender": "male"
            },{
                "passport": "qpuid5423",
                "inn": 123542
            }]
        }));
        this.add(new Student({
            student: [
            {
                "name": "john",
                "lastName": "fox",
                "middleName": "yonson"
            },{
                "age": 26,
                "gender": "male"
            },{
                "passport": "qpuid5423",
                "inn": 123542
            }]
        }));        
    }
});

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: $('body'),
    initialize: function () {
        _.bindAll(this, 'render');
        this.group = new Group();
        this.render();
    },
    render: function () {
        var $ul = $('<ul>').addClass('student-list');

        _.each(this.group.models, function (element, i) {
            var studentView = new StudentView({
                model: this.group.models[i]
            });
            $ul.append(studentView.render().el);
        });
        thi.$el.append($ul);
    }
});
var groupView = new GroupView();

我需要学生模型中的那个奇怪的方法getConvertedHash(),这样我就可以获得一个散列而不是一组对象(作为我的初始数据结构:需要它用于进一步的目的)。

您输入错误,错误是 属性 models 不存在。在你的 render 函数中它不应该说 this.group.models 它应该说 this.group.model.

render: function () {
    var $ul = $('<ul>').addClass('student-list');

    _.each(this.group.model, function (element, i) { // here
        var studentView = new StudentView({
            model: this.group.model[i] // and here
        });
        $ul.append(studentView.render().el);
    });
    this.$el.append($ul); // also "this" was mistyped
}

您想要的是按照预期的方式使用 .each 迭代器:

this.group.each(function (model) {
    var studentView = new StudentView({model: model});
    $ul.append(studentView.render().el);
});