我想从我的收藏中渲染每个服务员,但是控制台仍然显示错误:
未捕获的TypeError:无法调用未定义的方法'toJSON'
这是我的代码:
(function() {
window.App = {
Models: {},
Views: {},
Collections: {}
};
window.template = function(id) {
return _.template( $('id' + id).html() );
},
//等待模型
App.Models.Waiter = Backbone.Model.extend({
defaults: function() {
return {
title: 'Waiter Name',
id: []
};
}
});
//等待收集的列表
App.Collections.Waiters = Backbone.Collection.extend({
model: App.Models.Waiter
});
//查看所有等待者
App.Views.Waiters = Backbone.View.extend({
tagName: 'ul',
render: function() {
this.collection.each(function(waiter) {
var waiterView = new App.Views.Waiter({ model: waiter });
this.$el.append(waiterView.render().el);
}, this);
return this;
}
});
//一个人的视图
App.Views.Waiter = Backbone.View.extend({
tagName: 'li',
template: _.template("<%= title %><%= id %>"),
render: function() {
this.$el.html( this.template(this.model.toJSON()) );
return this;
},
});
waitersCollection = new App.Collections.Waiters([
{
title: 'ferko fristansky',
id: 2
},
{
title: 'ferko bandaska',
id: 3
},
{
title: 'fvwerv fristansky',
id: 4
}
]);
var waitersView = new App.Views.Waiter({ collection: waitersCollection });
$(document.body).append(waitersView.render().el);
})();
答案 0 :(得分:1)
您正在使用集合创建waiterView
:
var waiterView = new App.Views.Waiter({ collection: waitersCollection });
但App.Views.Waiter
是基于模型的视图;这意味着this.model
中的undefined
将App.Views.Waiter
,因此会失败:
this.$el.html( this.template(this.model.toJSON()) );
// this is undefined -------------^^^^^
您可能想要创建一个App.Views.Waiters
:
var waitersView = new App.Views.Waiters({ collection: waitersCollection });
然后,在App.Views.Waiters
内,您为集合中的每个模型创建一个App.Views.Waiter
而不是new App.Views.extend({ model: waiter })
:
render: function() {
this.collection.each(function(waiter) {
var waiterView = new App.Views.Waiter({ model: waiter });
this.$el.append(waiterView.render().el);
}, this);
return this;
}
顺便说一句,请小心:
App.Models.Waiter = Backbone.Model.extend({
defaults: {
title: 'Waiter Name',
id: []
}
});
来自defaults
的值被浅层复制,因此使用这些默认值的所有内容最终将使用完全相同的id
数组,当您有多个模型共享相同的id
数组时,这会导致奇怪的错误1}}数组。如果defaults
中有可变值,则通常需要使用函数,以便每个人都获得自己的不同值:
App.Models.Waiter = Backbone.Model.extend({
defaults: function() {
return {
title: 'Waiter Name',
id: []
};
}
});