gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot call method 'toJSON' of undefined in backbone

转载 作者:行者123 更新时间:2023-11-28 01:32:57 25 4
gpt4 key购买 nike

      var Person = Backbone.Model.extend({
defaults: {
name: "John Doe",
age: 27,
designation: "worker"
},
initialize : function(){
this.on("invalid",function(model,error){
alert(error);
});
},
validate: function(attrs){
if(attrs.age < 0){
return 'Age must be positive,stupid';
}
if( ! attrs.name ){
return 'Name should not be empty';
}
},

work: function(){
return this.get('name') + ' is a ' + this.get('designation');
}
});

var PersonCollection = Backbone.Collection.extend({
model: Person
});

var peopleView = Backbone.View.extend({
tagName: 'ul',
render: function(){
//filter through all the items in a collections
//for each, create a new PersonView
//append it to root element

this.collection.each(function(person){
//console.log(person);
var personView = new PersonView({model:person});
this.$el.append(personView.render().el);
},this);
}
});

// The view for a Person
var PersonView = Backbone.View.extend({
tagName : 'li',
className : 'person',
id : 'person-id',
template: _.template( $('#personTemplate').html() ),
initialize : function(){
_.bindAll(this,'render');
//console.log(this.model)
this.render();
},

render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});

var modelperson = new Person;
var viewperson = new PersonView({model : modelperson});

var personCollection = new PersonCollection([
{
name: "raghu",
age:24
},
{
name: "shashank",
age:23,
designation: "CTO"
},
{
name : "junaid",
age : 30,
designation : "UI"
},
{
name: "vishnu",
age: 23,
designation: "content developer"
}

]);

var peopleView = new PersonView({collection: personCollection});

我收到了诸如调用“toJSON”未定义之类的错误,我不知道如何摆脱这个错误。

最佳答案

您需要在 View 中传递模型

更改代码的最后一行

var peopleView = new PersonView({collection: personCollection});

var peopleView = new PersonView({collection: personCollection,model:new Person()});

Demo

已更新,我认为它是 peopleView 而不是 personView 所以最后一行应该是这样的,

 var pw = new peopleView ({collection: personCollection});
pw.render();

那么您需要更改您的peopleveiw,例如,

var peopleView = Backbone.View.extend({
tagName: 'ul',
render: function(){
//filter through all the items in a collections
//for each, create a new PersonView
//append it to root element

this.collection.each(function(person){
//console.log(person);
var personView = new PersonView({model:person});
this.$el.append(personView.render().el);
},this);
// apend the element to body if not exists
$(this.$el).appendTo('body');
}
});

Updated Demo

关于javascript - 未捕获的类型错误 : Cannot call method 'toJSON' of undefined in backbone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21899338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com