我是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()
,所以我可以得到一个哈希而不是一个对象数组(作为我的初始数据结构:需要它用于其他目的)。
答案 0 :(得分:1)
您错误输入了错误,错误是属性export PS1=">"
不存在。在models
功能中,它不应该说render
它应该说this.group.models
。
this.group.model
答案 1 :(得分:1)
你想要的是按照预期的方式使用.each
迭代器:
this.group.each(function (model) {
var studentView = new StudentView({model: model});
$ul.append(studentView.render().el);
});