Reputation: 157
I'm new to Backbone and am trying accomplish some simple tasks, such as rendering list of names from the model. But I'm getting this error:
'cannot read property "model" of undefined'
I would really appreciate any help with this and any tips in general.
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();
I need that strange method getConvertedHash()
in a Student Model so I can get one hash instead of an array of objects (as my initial data structure: need it for further purposes).
Upvotes: 1
Views: 47
Reputation: 3091
What you want is to use the .each
iterator the way it is intended to be used:
this.group.each(function (model) {
var studentView = new StudentView({model: model});
$ul.append(studentView.render().el);
});
Upvotes: 1
Reputation: 5815
You mistyped your error, the error is that the property models
doesn't exist. Inside your render
function it shouldn't say this.group.models
it should say 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
}
Upvotes: 1